javascript 删除 Backbone 视图的所有事件侦听器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12965907/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:31:38  来源:igfitidea点击:

Remove all event listeners of a Backbone view

javascriptbackbone.js

提问by Michael

Is there a way to remove all event listens instantiated by a backbone view? For example, suppose I have the following HTML/JavaScript. When #box is clicked, I want a pop-up to say hello.

有没有办法删除由主干视图实例化的所有事件监听?例如,假设我有以下 HTML/JavaScript。当点击#box 时,我想要一个弹出窗口来打招呼。

<div id="box" style="height: 100px; width: 100px; background-color: red"></div>

var Listener = Backbone.View.extend({
    el: "#box",
    events:  {
        'click #box' : 'hello'
    },
    hello: function () {
        alert('hello!');
    }
})

var listener = new Listener();

Now, I want to remove the event listener. Setting listener to something else doesn't work:

现在,我想删除事件侦听器。将侦听器设置为其他内容不起作用:

listener = ''; // doesn't work

How do I remove the event listener?

如何删除事件侦听器?

回答by Matt Stone

Anywhere in your View:

您视图中的任何位置:

this.undelegateEvents();

You can then manually rebind events at a later time with delegateEvents();

然后,您可以稍后手动重新绑定事件 delegateEvents();

I use a method added to the Backbone.View prototype to easily clean up views:

我使用添加到 Backbone.View 原型的方法来轻松清理视图:

Backbone.View.prototype.close = function() {
    this.undelegateEvents();
    this.remove();
}

// internal usage
this.close();

// external usage
myView.close();


EDIT 19/07/2013

编辑 19/07/2013

Backbone v0.9.9 added the .listenTo()method to views, making it easy to unbind external events when the view is removed.

Backbone v0.9.9 在.listenTo()视图中添加了该方法,可以在视图移除时轻松解除外部事件的绑定。

You can read more here:

你可以在这里阅读更多: