最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove all event listeners of a Backbone view - Stack Overflow

programmeradmin6浏览0评论

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.

<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?

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.

<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?

Share Improve this question edited Apr 2, 2014 at 14:52 Matthieu Riegler 55.4k25 gold badges145 silver badges197 bronze badges asked Oct 19, 2012 at 0:52 MichaelMichael 2,0516 gold badges22 silver badges27 bronze badges 1
  • 1 May be you can have a look at an article by Derick Bailey. – Cyclone Commented Oct 19, 2012 at 5:21
Add a ment  | 

1 Answer 1

Reset to default 14

Anywhere in your View:

this.undelegateEvents();

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

  • http://backbonejs/#View-delegateEvents
  • http://backbonejs/#View-undelegateEvents

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

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

// internal usage
this.close();

// external usage
myView.close();

EDIT 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.

You can read more here:

  • Backbone.js - listenTo() documentation
  • StackOverflow - Backbone 0.9.9: Difference between ListenTo and on
发布评论

评论列表(0)

  1. 暂无评论