tying button onclick event to Backbone View

Go To StackoverFlow.com

0

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 event handler to remember 'this' as the backbone view, not the element that it was called on. No matter how much docs I read, I cant seem to make it past this mental hump.

in my view, I have

initialize: function() {'
  //i am trying to say, call render on this view when the button is clicked. I have tried all of these calls below.
  //this.$("#add-tweet-button").click(this.render); 
  //this.$("#add-button").bind("click", this.render);

}

When the render function is called, the 'this' element is the button. I know what im missing is pretty easy, can someone help me out with it? Also, is this sound as coding conventions go?

2012-04-03 22:38
by Ying


4

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 function
    return this;
  }
});

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.

2012-04-03 23:06
by Edward M Smith


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...
    }       

});
2012-04-04 06:55
by drinchev