2015-06-03 19 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'与这个问题有什么关系? –