[英]Unbind Backbone View Events
I have the falling events hash - 我有下降事件哈希-
events:
'click #someButton : 'someFunction'
To close the view I have tried 关闭我尝试过的视图
close:
$("#someButton").unbind("click")
and 和
`close:
$("#someButton").remove()`
But someFunction is still being fired more than once. 但是someFunction仍然被多次触发。 How do I unbind this event from the button?
如何从按钮取消绑定此事件?
I've also tried 我也尝试过
$(@el).find("#someButton").unbind("click") as well
Backbone.js view events are delegated to the view's el
(so there is no event bound to your #someButton
element but rather when a click event bubbles up to the el
it checks to see if the event came from an element matching that selector), that being the case to remove the event you need to remove it from the el
, for example Backbone.js视图事件被委托给视图的
el
(因此,没有事件绑定到#someButton
元素,而是当click事件冒泡到el
它会检查该事件是否来自与该选择器匹配的元素),例如,要删除该事件,您需要将其从el
删除,例如
$(this.el).off('click', '#someButton');
If you want to remove all delegated events you can just use the view's undelegate method 如果要删除所有委托事件,则可以使用视图的undelegate方法
Jack's explanation and answer are great. 杰克的解释和回答很棒。 Unfortunately, his code example didn't work for me.
不幸的是,他的代码示例对我不起作用。 Instead of using:
而不是使用:
$(this.el).off('click', '#someButton');
I had to use: 我不得不使用:
this.$el.off('click', '#someButton');
which makes sense to me, because the event was bound to this.$el
object. 这对我来说很有意义,因为该事件已绑定到
this.$el
对象。
To add further, I used this.$el.off();
为了进一步说明,我使用了
this.$el.off();
inside an initialize within a subview to destroy all events tied to the subview. 在子视图中的初始化内部,以销毁与该子视图相关的所有事件。 The same event would fire X number of times a data refresh was called.
相同事件将触发X次调用数据刷新的次数。
I saw the duplicated targets using: 我看到重复的目标使用:
var $target = $(e.currentTarget);
console.log($target);
I would add a comment to an answer, but I have low reputation. 我会在答案中添加评论,但我的声誉不高。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.