BackboneJS Declarative Events

Today I merged into my BackboneKIT project a piece of code from backbone.declarative GitHub page to implement declarative events into Views.

The BackboneJS way:

var myView = Backbone.View.extend({
    events: {
        'click' : 'onClick'
    },
    initialize: function() {

        // Listen to related model's events:
        this.model.on( 'change', this.onModelChange, this );

        // Listen to views's triggered events:
        this.on( 'statusChange', this.render, this );
    },

    // Callbacks
    onClick: function() {},
    onModelChange: function() {},
    render: function() {}
});

The BackboneKIT way (declarative events):

var myView = Backbone.View.extend({

    // Declarative events:
    events: {
        'click' : 'onClick'
    },
    modelEvents: {
        'change' : 'onModelChange'
    },
    viewEvents: {
        'statusChange' : 'render'
    },

    // Callbacks
    onClick: function() {},
    onModelChange: function() {},
    render: function() {}
});

Declarations over Initializations

I think BackboneKIT works better with declarative events because this way you expose what event and what handlers to listen/use. It is more DRY than code them into the initialize() method!

Implicit Inheritance Your events

declarations are inherited from child objects! Child objects inherits events and may add new events or override existing handlers.

viewEvents

Respond to events triggered to the view itself.
This is really useful because parent’s view, chidren views, global UI components may trigger events on the view itself.

Now you can listen to these events!

parentEvents

Works like viewEvents but focusing on parent view. If exists.

modelEvents

Respond to events triggered to the associated model. If exists.

collectionEvents

Respond to events triggered to the associated collection. If exists.

Powered By DT Author Box

Written by MPeg

MPeg

Hi, i’m Marco (aka MPeg) and i’m very appassionate in web interfaces developing. I like so much code style and optimization. I spoke PHP, Javascript, HTML5, CSS3 My best friends are CakePHP, CakePOWER, jQuery, LESS, TwitterBootstrap, Underscore, Backbone, Sencha Touch, jQueryUI, jQuery Mobile.

Author’s Website

Posted in BackboneJS and tagged , , , , , , , , . Bookmark the permalink. RSS feed for this post. Leave a trackback.

Swedish Greys - a WordPress theme from Nordic Themepark.