I’m working on a Backbone.js web application with a few different views. Let’s say we have the AudioPlayer view at the top of the page that should be persistent and play audio while the rest of the page content changes. The rest of the page content should be able to be switched on demand (with the Router updating the url via navigate).
I’m looking for the correct way to hide/remove FirstView, insert a SecondView, and then hide/remove SecondView and insert/show FirstView again when the user clicks the “back” button.
I’ve been told that views should be removed when they are not shown to avoid memory leaks. If this is true, what’s the proper way to re-create the view again, as its associated view.el has been destroyed during the remove process? Or is there a more logical way to do this?
This is the way I do it:
openthat will append the view to the DOM as well as set a flag on the view that is now open, and a similarclosepropertyviewsproperty of your appclearViewson the app that will close all open views except the view names passed inHere is a gist (in coffeescript) of what I’ve been using. Feel free to copy.
https://gist.github.com/4597528
So after extending Backbone in this way, lets suppose you want to create and open a new view in a Backbone route after closing all open views except the top nav bar, which app.views.topNav points to. You can say:
There are some great view and layout managers out there for larger projects like Marionette by Derick Baily and LayoutManager by Tim Branyen, but they seemed like overkill for my smaller projects.