将按钮onclick事件绑定到Backbone视图

问题描述:

我在Backbone中有一个示例单页面应用程序,我正在搞乱。这个想法是,我有一个按钮,将触发视图刷新。我试图让事件处理程序记住'this'作为骨干视图,而不是它被调用的元素。无论我读了多少文件,我似乎都无法通过这个精神峰会。将按钮onclick事件绑定到Backbone视图

在我看来,我有

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); 

} 

当渲染函数被调用时,“这个”元素是按钮。我知道我缺少的东西很容易,有人可以帮我解决吗?另外,这是否符合编码惯例?

如果您使用视图的“delegateEvents”功能,该作用域是照顾你:

var yourView = Backbone.View.extend({ 

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

    render: function() { 
    // your render function 
    return this; 
    } 
}); 

这仅适用于那些“下”视图的EL元件。但是,你的例子显示了这个。$(...),所以我假设情况是这样的。

@Edward中号史密斯是正确的,但如果你需要处理元素的一个jQuery事件视图的范围之内你可能会写这样的说法:

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

});