如何在主干中动态生成的按钮上绑定事件? [英] How to bind events on dynamic generated buttons in backbone?
问题描述
如何在backbone.js 中动态生成的按钮上绑定点击事件?
How do I bind click event on dynamic generated buttons in backbone.js?
window.PackageView = Backbone.View.extend({
tagName: "div",
className: "package-template",
events:{
'click #display-nodes' : 'main', // This button is declared in my HTML code and calls main method successfully.
'click .display' : 'disp', // This is dynamic button generated with class as display
},
getAction: function(nodeId){ // Get Actions from NodeId and generate buttons
$('.nodes').append("<button>" + action.Name + "</button>"); //Generate Buttons
$(".nodes button").addClass("display");
},
disp: function(){
alert("Inside Disp Function");
},
点击#display-nodes
时,节点会根据需要显示,但.display
不起作用.如何让这个按钮调用函数?
On clicking #display-nodes
the nodes are displayed as required but .display
is not working. How do I make this button call the function?
推荐答案
Backbone 视图可以通过 events
属性从动态生成的 DOM 元素接收事件,只要动态生成的 DOM 元素是视图的 el
的后代.相关代码在 delegateEvents() 中.它使用 jQuery 的 delegate() 选择器方法.
A Backbone view can receive events from dynamically generated DOM elements, through the events
property, as long as the dynamically generated DOM elements are descendants of the view's el
. The relevant code is in delegateEvents(). It uses jQuery's delegate() selector method.
它不适合您的最可能原因是新创建的 不是视图的
el
的后代.我说得对吗?
The most likely reason it's not working for you is that the newly created <button>
is not a descendant of the view's el
. Am I right?
如果是这种情况,并且您希望将元素保留在视图的 el
之外,则可以将其从视图的 events
属性中删除,并委托给其他元素您视图的 init
方法.
If this is the case and you want to keep the element outside of the view's el
, you can remove it from your view's events
property and delegate on another element in your view's init
method.
这篇关于如何在主干中动态生成的按钮上绑定事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!