2011-08-26 30 views
1

我想,當檢測到點擊鼠標數一個按鈕的頁面Backbone jQuery只能在Template中的元素上觸發事件?

var view=Backbone.View.Extend({ 
    template:_.template($("tem").html()), 
    events: { 
      "click button" : "foo" 
     }, 
    }) 

然後我把模板腳本里面按鈕上使用以下觸發功能,和外面的模板,它是一個簡單的直接生成HTML。

但是,它只在模板中的按鈕上註冊點擊,而不是直接的HTML按鈕。

如何解決這個問題?

回答

1

大概最容易做的事情是建立在你的初始化函數在視圖定義綁定,就像這樣:

var view = Backbone.View.Extend({ 
     template:_.template($("tem").html()), 
     events: { 
      "click button" : "foo" 
     }, 
     initialize: function() { 
      _.bindAll(this, 'foo'); //so foo's "this" is the view 
      $('selector to direct HTML button').delegate('click', this.foo); //so when the out-of-template button is clicked, the foo handler is called 
     } 
}) 
+0

我只是遵循Todo Backbone示例。 http://documentcloud.github.com/backbone/examples/todos/index.html它們就像我在委託事件時擁有的方式一樣。它一定是我遺漏的其他東西。另外,你的代碼給我一個錯誤 –

+0

這並不意味着被複制粘貼,而是作爲你的應用程序的指南。一般的方法是有效的。錯誤是因爲'this.foo'直接傳遞給'delegate'調用?您可能需要將其包裝在匿名函數中。 –

0

您需要正確指定EL在您的視圖。我沒有。 因爲事件{}調用jQuery委託函數。代表必然會以此爲根元素

+0

在我的情況下,我忘了$('#app')中的# –

相關問題