Wednesday 8 February 2012

Extending Backbone.js view using custom JavaScript namespacing

Backbone.js is an open source class library that enables an efficient client-side MVC implementation. Backbone shines if the requirement is to maintain a large collection of data on the client-side without the unnecessary round trips to the server.

I've been working on an ASP.NET MVC 3 project that involves quite a number of pages with similar look and feel. So instead of building every page from the ground up, we decided to developer a vanilla page and use it as a template for all other pages. Anyway, to encourage a reuse of the generic JavaScript file we'd come up with we split the Backbone views into separate files (ala UserControls) so we would reuse them in any other project.

We decided on a Namespacing strategy that would reduce tendency for method name collision.

To wrap a JavaScript class in a namespace;

Regedit.View = function(){
//Write your private functions here
//e.g. function myprivates() {}
return {
//Write your public functions here
//e.g mypublic: function(){}
};
}();
Note this will work only if you already have an existing "Regedit" namespaces already defined and referenced by this file. With this on place we could extend/inherit a Backbone view module like so;

Regedit.View = function () {
return {
extend: function (classProps) {
return Backbone.View.extend({
el: $("#someElement"),
initialize: function (customCollection) {
_.bindAll(this, "render"); //Enable This keyword in render method
//pass the view context on to the derived the derived class
//This will enable the derived class use the "this" keyword to refer this view
if(classProps.initialize != undefined){
classProps.initialize(this);
}
//this.models = customCollection;
},
template: $("#template"),
events: {
"change #someEvent": "SomeEventHandler"
},
SomeEventHandler: function(){
//this.contructor.someDerivedClassMethod();
}
}, classProps);
}
};
} ();

With our custom view in place, we can create a view using our custom module;

var newView = Regedit.View.extend({
//Custom view properties here
initialize: function(viewContext){ //this will be called from the base class
_.bind(viewContext, this.derivedClassMethod)
},
derivedClassMethod: function(){
this.someBaseClassMethod() //The "this" keyword will refer to the current view context
}
});

The class utilises the underscore.js library's _.extend method to extend/inherit a backbone view, but the same technique can be employed to extend a backbone model or collection as well.

This post is not a tutorial for Backbone.js. To learn more about or download Backbone.js, please visit the backbone.js website.

Happy coding.

No comments:

Post a Comment