最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - tying button onclick event to Backbone View - Stack Overflow

programmeradmin2浏览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?

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?

Share Improve this question edited Jun 25, 2014 at 12:57 Upperstage 3,7678 gold badges46 silver badges68 bronze badges asked Apr 3, 2012 at 22:38 YingYing 2,0005 gold badges25 silver badges38 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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.

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

});
发布评论

评论列表(0)

  1. 暂无评论