sábado, 26 de marzo de 2011

Playing with Backbone.js Views inheritance

One common requirement for big javascript applications is being able to create reusable and extensible visual components (Views in backbone).  The most natural way to achieve this extensibility goal in an OOP environment is to take advantage of inheritance capabilities available in javascript [1]. 

For example in my projects I usually create a PopupView class implementing the funcionality shared by all the popups (close button, resizing, modelness...) and then I create a XXXXPopupView class for each type of popup in my application.

I didn't find any documentation on how to implement this pattern with Backbone.js, and I've been playing with two different approaches to get it.

Proposal 1. Extending events property (doesn't require any change in backbone)

    var ViewClass = Backbone.View.extend({
      el: $("body"),
      events: {
        "click": "click"
      },
      click: function() {
      }
    });
    var SubviewClass = ViewClass.extend({
      events: _.extend({
        "dblclick": "dblclick"
      }, ViewClass.prototype.events),
      dblclick: function() {
      }
    });

    var view = new SubviewClass;

We have to admit that the resulting code could be nicer.

Proposal 2. Changing Backbone events declaration
Making some little changes in backbone.js you can get a simpler solution, although it also has some potential drawbacks.  I forked it in github to publish these changes [2].

    var ViewClass = Backbone.View.extend({
      el: $("body"),
      "click": function() {
      }
    });
    var SubviewClass = ViewClass.extend({
      "dblclick": function() {
      }
    });

    var view = new SubviewClass;

In this case the resulting code is much cleaner, although it requires the implementation in backbone.js of some heuristics in the views to differentiate the event declarations from other properties in the object.

I included some unit testing and also confirmed that all the existing backbone tests weren't broken, but I would be glad to receive any comments proposing better solutions to implement View inherintance.

[1] http://jupiterjs.com/news/writing-the-perfect-jquery-plugin
[2] https://github.com/ggarber/backbone

2 comentarios: