我正在为事件列表创建自定义事件。我在这样的文件(event.js)中有这些事件:
define(function(require, exports, module) {
module.exports = {
'event1': ['test1','data1'],
'event2': ['test2','data2']
};
});
我正在为每个事件创建事件触发器
createTriggers: function(Events){ //Events = require(event.js);
_.defer(function(){
_.each(Events,function(data,event){
var events = function () { console.log("Data is "+this.data)};
events = _.bind(events,data);
targ.events.bind(event,events); //targ is the Backbone event object
});
});
}
但是当我触发任何事件时:
this.trigger("event1");
我得到O / p,因为数据未定义。为什么值' [' test1',' data1']'是不是被抓了?
答案 0 :(得分:3)
考虑这两行:
var events = function () { console.log("Data is "+this.data)};
events = _.bind(events,data);
假设此时data
是一个数组(['test1','data1']
),您的代码会执行此操作:
console.log("Data is " + ['test1','data1'].data);
你可能想要:
var events = function () { console.log("Data is "+this)};
events = _.bind(events,data);
或
var events = function () { console.log("Data is "+this.data)};
events = _.bind(events,{data: data});
有关更多示例,请参阅下划线绑定documentation。