删除Backbone事件的侦听器

时间:2016-09-15 21:53:50

标签: javascript backbone.js backbone-events

我想知道如何删除Backbone.history.on()的监听器? .off()对我不起作用。

Backbone.history.on('all', function() {
  doStuff();
});

1 个答案:

答案 0 :(得分:3)

off可以正常工作,这里有Router证明了这一点:

var MyRouter = Backbone.Router.extend({
    routes: {
        'off': 'offAll',
        '*actions': 'index',

    },

    initialize: function(opt) {

        Backbone.history.on('all', this.all);
    },

    index: function() {
        console.log('route');

    },

    offAll: function() {
        console.log('offAll');

        // remove only this one listener
        Backbone.history.off('all', this.all);
    },

    all: function(){
        console.log('all test');
    }

});

导航到#/off以外的任何内容都会显示:

route
all test

然后,导航到#/off将显示:

offAll

然后,all test永远不会出现。

Backbone的事件.off功能

// Removes just the `onChange` callback.
object.off("change", onChange);

// Removes all "change" callbacks.
object.off("change");

// Removes the `onChange` callback for all events.
object.off(null, onChange);

// Removes all callbacks for `context` for all events.
object.off(null, null, context);

// Removes all callbacks on `object`.
object.off();