Saturday, September 29, 2012

Backbone.js View Events not Firing?


In backbone, setting the el element in the view's initialize method doesn't ensure that the events are bound correctly. Apparently the events are wired only when the el element is set via the views constructor as an option, which is not always what you'd like to do.

To workaround, if your setting the el element in the initialize method of the view, then make sure you call this._ensureElement() right after.

_ensureElement() methods description says this :

Ensure that the View has a DOM element to render into. If `this.el` is a string, pass it through `$()`, take the first  matching element, and re-assign it to `el`. Otherwise, create an element from the `id`, `className` and `tagName` properties.

var MyView = Backbone.View.extend({
       'events': {
                'click .next': 'next',
                'click .cancel': 'cancel'
        },
  
        'initialize': function() {
            this.el = $('#step1');
            this._ensureElement();
            _.bindAll(this, 'render');
             this.template = _.template($('#step1-template').html());
            this.render();
        },
        
        'render': function() {
            $(this.el).html(this.template(this.model.toJSON()));
            return this;
        }, 

       'next': function(){
           window.console.log('next');
       },
  
       'cancel': function(){
            window.console.log('cancel');
       }
 });