I\'m currently working on a large web app built on backbone.js and have been having a lot of issues with organization, \"zombies,\" etc. so I\'ve decided to do a major refactor
I namespace similar to what you're doing (at least for the classes part) and all my models, views, and controllers look like this:
views/blocks.js:
(function(cn){
cn.classes.views.blocks = cn.classes.views.base.extend({
events: {},
blocksTemplate: cn.helpers.loadTemplate('tmpl_page_blocks'),
initialize: function(){
},
render: function(){
$(this.el).html(this.blocksTemplate());
},
registerEvents: function(){},
unregisterEvents: function(){}
});
})(companyname);
My JavaScript namespace looks like this, though I do improve upon it every time I build a new app:
companyname:{
$: function(){}, <== Shortcut reference to document.getElementById
appView: {}, <== Reference to instantiated AppView class.
classes = { <== Namespace for all custom Backbone classes.
views : {},
models : {},
collections: {},
controllers : {},
Router: null
},
models: {}, <== Instantiated models.
controllers: {}, <== Instantiated controllers.
router: {}, <== Instantiated routers.
helpers: {}, <== Reusable helper platform methods.
currentView: {}, <== A reference to the current view so that we can destroy it.
init: function(){} <== Bootstrap code, starts the app.
}
Anything I want all my views to have, I put in the base view. My controller will call registerEvents
on any new view it creates (after render) and unregisterEvents
on a view right before it kills it. Not all views have these two extra methods so it first checks for the existence.
Don't forget that all views come with a this.el.remove();
built in. Which not only kills the views container element but unbinds all events attached to it. Depending on how you are creating your views through your controller you may not actually want to kill the element and do this.el.unbind() instead to unbind all events.