Monday, November 21, 2011

Using Backbone.js views as a class structure

So what I’ve ended up doing is using Backbone.js Views basically as a class structure.  I used to use immediate functions or static objects or whatever you want to call them, basically

var x= (function(){

return {

}

}())

for everything.  And I always had an init function to set it up.  The limitation was that I could not inherit from those classes so I eneded up duplicating code a lot.

So, as I was saying, I’ve adopted backbone.js views as my class structure.  I can inherit these classes, they are constructor functions so I can put set up code in the function and they offer a few bonus features as well, such as if I have straight up events I can use the views event declaration infrastructure.  But overall what I like the most about it is that I can create base classes that have the functionality that I use a lot on them.  Now I know I could write my own class structure and implement all these features as well as a couple I’m about to mention that I don’t like, myself, but a) I’m kind of scared of constructer functions with prototypal inheritance and b) I believe ( hope ) that the structure will be familiar to people who use backbone.js ( such as my team ) and they will understand what is going on more easily.

The one thing I don’t like about using backbone.js views as my base class structure, is that it doesn’t implement any override functionality.  You can overwrite but not override and call base().  This would be great for such things as having a function on a base class called registerSubscriptions() that lays out the common subscription.  Then in my inhertied classes I could override it add page specific subscriptions then call base().

The way I get around that now ( and there are I guess a couple of similarly distateful ways ) is that I have my base registerSubscriptions() call registerAdditionalSubscriptions() as it’s last step.  in the base class I stub out the method so it won’t crash and in my sub classes I overwrite the method if necessary.

No comments: