Making life easier with BackSupport

When I first started working with Backbone a few years ago, I was inspired to write BackSupport (https://github.com/machineghost/BackSupport) to help eliminate a lot of boilerplate code that I found myself writing over and over again. For instance, consider this basic View class:

var BookView = ParentBookView.extend({
    className: ParentBookView.prototype.className + ' book-view',
    initialize: function(options) {
        this.template = options.template ;
        if (!this.template ) {
            throw new Error('The template option is required!'),
        }
        _.bindAll(this, ''render'),
    },
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
   }
});

Now, what if there were a way to reduce all that common code to just the parts that are specific to our class? This is where BackSupport comes in. Let's look at that same View class recreated using BackSupport:

BookView = ParentBookView.extend2({
    boundMethods: ['render'],
    className: "book-view",
    propertyOptions: ['template'],
    requiredOptions: ['template'],
});

As you can see, BackSupport simplified so much of our logic that we didn't even need an initialize method in our second version!

Here are all of the BackSupport features demonstrated:

  • extend2: This alternate form of Backbone's extend is smart enough to combine, rather than replace, properties such as className, events, or defaults. This allows you to more easily create subclasses that use these properties, without losing their values from the parent class.
  • boundMethods: BackSupport will automatically call _.bindAll on every method included in this property, so we don't have to do it manually in an initialize method.
  • propertyOptions: BackSupport will automatically transform any option included in this property into a new property of instances of this class, saving us from the tedium of doing this.foo = options.foo in our initialize.
  • requiredOptions: BackSupport will throw an error if a class is instantiated without providing these options, giving us a simple way to ensure that they are provided without adding extra initialize logic.
  • render: BackSupport provides a set of methods to make using templates easier. These methods are completely agnostic as to which templating system you use, and to choose a particular templating system, you need to only override the relevant BackSupport methods.

While this simple example provides a taste of what BackSupport offers, it also has many other great convenience features, which you can learn about on its GitHub page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.127.57