javascript 取消绑定主干视图事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12359604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unbind Backbone View Events
提问by praks5432
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. How do I unbind this event from the button?
但是 someFunction 仍然不止一次被触发。如何从按钮取消绑定此事件?
I've also tried
我也试过
$(@el).find("#someButton").unbind("click") as well
回答by Hyman
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
元素,而是当单击事件冒泡到el
它时,它会检查事件是否来自与该选择器匹配的元素),就是这种情况删除你需要从删除的事件el
,例如
$(this.el).off('click', '#someButton');
If you want to remove all delegated events you can just use the view's undelegatemethod
如果你想删除所有委托的事件,你可以使用视图的undelegate方法
回答by Rafael Eyng
Hyman's explanation and answer are great. Unfortunately, his code example didn't work for me. Instead of using:
Hyman的解释和回答很棒。不幸的是,他的代码示例对我不起作用。而不是使用:
$(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
对象。
回答by Chad
To add further, I used 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.
为了进一步补充,我this.$el.off();
在子视图中的初始化中使用来销毁与子视图相关的所有事件。同一事件将触发 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.
我会在答案中添加评论,但我的声誉很低。