2012-04-03 37 views
0

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

} 

當渲染函數被調用時,「這個」元素是按鈕。我知道我缺少的東西很容易,有人可以幫我解決嗎?另外,這是否符合編碼慣例?

回答

4

如果您使用視圖的「delegateEvents」功能,該作用域是照顧你:

var yourView = Backbone.View.extend({ 

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

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

這僅適用於那些「下」視圖的EL元件。但是,你的例子顯示了這個。$(...),所以我假設情況是這樣的。

2

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

});