2013-11-22 56 views
-1

骨干事件事件执行后仍束缚,object.off触发骨干事件没有触发关闭方法

PFB的代码

var object = _.extend({}, Backbone.Events); 

object.off('app:test:load', function() { 
    console.log("========my foot======="); 
}, this); 
object.on('app:test:load', function() { 
    //fn calls 
}); 

object.trigger('app:test:load'); 

所有的心思都欢迎抽象后不执行,谢谢提前。

回答

2

没有与此代码的多个问题,因为它提出:

  • 关闭方法被称为之前功能被注册,所以它是可以理解的,该触发器将调用日志或其他呼叫
  • 匿名函数传递给。匿名功能可与不同的倍率的仅移除掉功能
  • 被送入关闭,对于写在这样的方式代码,将指向父对象(可能甚至窗口),所以代码实际上将尝试从一些其他的东西删除回调,不对象

工作实例可能脱落在这个问题上的一些光:

// create object which support events 
var object = _.extend({}, Backbone.Events); 

// define function as non-anonymous 
var doAction = function() { 
    console.log("========my foot======="); 
}; 

// function has to be registered first (cannot remove something that is not there) 
object.on('app:test:load', doAction); 

// register another function to illustarate removal of anonymous functions 
object.on('app:test:load', function(){ 
    console.log("from anonymous"); 
}); 

// will invoke both functions 
object.trigger('app:test:load'); 

// example 1: only remove this particular function for this particular trugger 
object.off('app:test:load', doAction); 

// will invoke only anonymous, since first one was removed 
object.trigger('app:test:load'); 

// example 2: only remove ALL registered functions for this trigger 
object.off('app:test:load'); 

// will not write anything 
object.trigger('app:test:load'); 
+0

我知道这是一个旧的,但好奇,你可以做'.on('app:test:load',myFunc(var1))'和'.on('app:test:load',myFunc var1,var2))''然后只删除一个参数? '.off('app:test:load',myFunc(var1)''或者只对*命名不同的函数有效。'.off('app:test:load',myFunc'会同时删除吗? – redfox05