我问这个问题是因为我觉得有一种更简洁的方法来解决这个问题,而不是使用匿名函数来包裹这个问题。
// This does not work because it passes the value found
// at obj.init at the time of binding.
scope.on('anEvent', obj.init);
// This works because it is wrapped in the anonymous function and the
// obj.init method that gets run is whatever it is currently defined as.
scope.on('anEvent', function() { obj.init(); });
我希望每当' anEvent'时都要调用最新的方法(obj.init)。被发射出来。
答案 0 :(得分:1)
您没有绑定变量,您正在绑定值。原始obj.init
此时将值绑定为事件处理程序。您无法绑定“变量”并在以后重新评估其值。要在事件触发时重新评估变量,这确实是最直接的选择:
scope.on('anEvent', function() { obj.init(); });
答案 1 :(得分:0)
首次实施的问题是:
var obj = {};
scope.on(event, obj.callback)
obj.callback = function(){ console.log('this function wont be called on event'); };
obj
变量var obj = {
callback: function() { console.log(this.str); },
str: 'This string wont be sent out'
}
this.str = 'Maybe this is the one to come out';
scope.on(event, obj.callback);