删除 Backbone 事件的侦听器
Remove listener for a Backbone event
我想知道如何删除 Backbone.history.on()
的侦听器? .off()
对我不起作用。
Backbone.history.on('all', function() {
doStuff();
});
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();
我想知道如何删除 Backbone.history.on()
的侦听器? .off()
对我不起作用。
Backbone.history.on('all', function() {
doStuff();
});
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();