2016-09-15 94 views
1

我在想如何去除监听器到Backbone.history.on().off()没有为我工作。去除骨干事件的监听器

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

回答

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从来没有出现。

骨干事件.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(); 
+0

我怎么能保证我只能删除一个匿名函数? – Jon

+0

@Jon我编辑了我的答案,包括所需的行为。 –