2015-06-03 64 views
2

如何在將集合呈現到視圖後添加更多事件。主幹在渲染後添加更多事件?

我有一個需要綁定到它們的事件的所有元素ID的列表。

當前我正在嘗試使用jQuery onclick來觸發我的視圖中的函數回調。

雖然問題是我的視圖中的函數調用在jQuery click事件中是未定義的。

我看着骨幹文檔和它說,使用delegateEvents但是文件沒有顯示例子....

http://documentcloud.github.io/backbone/#View-delegateEvents

//add more dynamic events for the rendered employee list 
    addMoreEvents: function() 
    { 
     console.log("List View - Add More DOM Events"); 


     for (var i = 0; i < this.employees.models.length; i++) 
     { 
      var element = "#" + this.employees.models[i].attributes.id; 
      //bind event that when user clicks on <li> on employeelist , it will go fetch all the tasks for that employee 
      $(element).click(this.getEmployeeInfo()); //not working! 
     } 


    } 

必須有一個簡單的方法來添加做到這一點事件渲染後存在的元素。

謝謝

回答

2

你會這樣做的錯誤方式。與其試圖直接綁定點擊#some-id元素上的事件,您應該將類​​添加到要單擊的對象上,然後使用視圖的普通events對象將點擊處理程序綁定到該類的元素。

例如,你有這樣的事情在裏面您的視圖的el的HTML:

<li class="item" id="6">Where</li> 
<li class="item" id="11">is</li> 
<li class="item" id="23">pancakes</li> 
<li class="item" id="42">house?</li> 

,然後你不得不events像這樣在您的看法:

events: { 
    'click .item': 'getEmployeeInfo' 
} 

然後您的點擊處理程序getEmployeeInfo可以查看ev.currentTarget.id以獲取被點擊項目的id屬性:

getEmployeeInfo: function(ev) { 
    var id = ev.currentTarget.id; // this will be the model's `id` 
    // do whatever needs to be done... 
} 
+0

謝謝,這工作得很好。 請將此代碼添加到您的問題來顯示如何訪問dom元素 'ev.currentTarget.getAttribute(「attributename」);' – kaleeway

+0

getAttribute'與這個問題有什麼關係? –