I want to use BackboneJS for single page sites. The structure I am thinking of using is have a div#pageWrapper for loading views into
# a simple example view
class View1 extends Backbone.View
render: ->
@$el.html @template()
class AppRouter extends Backbone.Router
routes:
"": "home"
"view1": "view1"
"view2": "view2"
home: ->
# init, render, attach to body. repeat for other controller actions
view = new HomeView()
view.render()
$("#pageWrapper").html view.el
Is the the usual way of doing this? Or is there some kind of design pattern alreay available? I havent handled the clean up, do I need it? Or is it a side effect of simply replacing the page wrappers’ html?
Yes, you definitely need to handle closing of views and removing of them properly. If you don’t, you’ll end up with memory leaks and “zombie” views – views that should be dead, but aren’t.
I’ve written about it extensively:
http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/
http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
The gist of it is that you should manage cleaning up your view within your view directly, and then use a standardized process to call your view’s cleanup method.
For example, I use an object to show / remove / replace my views on the screen:
Just be sure your view has a
closemethod in it, and this code will clean it up for you. A simplecloseimplementation would look like this:and now all of your views have this close method.
See the articles for more information.