Monday, November 21, 2011

How I use Backbone.js Views as modules

In my previous post I explained how I use views as a basic class structure. Here I will go a bit deeper into how I use them.

At the base there is the traditional Backbone.js view.  Used as one would normally use it, to set up the container, hook up the events, and structure your code.  This is a nice way of compartmentalizing functionality.  But let’s say that you have two views, or pieces of functionality, say a popup functionality and an ajax form functionality.  You  could initialize the two views separately and then hook them together using a controller ( more on that later ) but if you do this a lot, and this is the sort of thing one would do a lot if they are using popups, then this get’s terribly tedious. 

So I employ what I call a module.  It’s an extended view that has a views collection ( object ) a modules collection and a destroy function();  Then I inherit this module, and in it I instantiate the ajax form view, the the popup view put the form in the popup and render. I put both views in the modules view collection.  The destroy method loops through the modules and the views that belong to the module and calls destroy and remove on them respectively.  Now I can call new AjaxPopupModule() pass in an el ( a root element ) and a url and possibly other stuff and I’m all set.

No comments: