删除Backbone事件的侦听器

c3frrgcw  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(214)

我想知道如何删除Backbone.history.on()的侦听器?.off()不适合我。

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

brqmpdu11#

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();

相关问题