Backbone.js : 将参数关联到事件回调函数

Backbone.js : Associating params to events callback function

我正在为事件列表创建自定义事件。我将这些事件保存在一个文件 (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");

我得到输出,因为数据未定义。为什么未获取值“['test1','data1']”?

考虑到这两行:

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