Skip to content Skip to sidebar Skip to footer

Tying Button Onclick Event To Backbone View

I have a sample single-page-application in Backbone that I am messing around with. The idea is that I have a button that will trigger a refresh on a view. I am trying to get the ev

Solution 1:

If you use the View's 'delegateEvents' functionality, the scoping is taken care of for you:

var yourView = Backbone.View.extend({

  events: {
    "click #add-tweet-button" : "render"
  },

  render: function() {
    // your render functionreturnthis;
  }
});

This only works with elements that are 'under' the View's El. But, your example shows this.$(...), so I'm assuming this is the case.

Solution 2:

@Edward M Smith is right, although if you need to handle a jquery event of element outside the scope of your View you might write it that way :

var yourView = Backbone.View.extend({

    initialize: function() {
        var self = this;
        $("button").click(function () {
              self.render.apply(self, arguments);
        });

    },

    render: function(event) {
        // this is your View here...
    }       

});

Post a Comment for "Tying Button Onclick Event To Backbone View"