2016-09-15 106 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我編輯了我的答案,包括所需的行爲。 –