3

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?

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
Michael
  • 2,031
  • 6
  • 21
  • 27
  • 1
    May be you can have a look at [an article](http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/) by [Derick Bailey](http://lostechies.com/derickbailey/author/derickbailey/). – Cyclone Oct 19 '12 at 05:21

1 Answers1

14

Anywhere in your View:

this.undelegateEvents();

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

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:

Community
  • 1
  • 1
Matt Stone
  • 3,705
  • 4
  • 23
  • 40