0

我正在爲事件列表創建自定義事件。我有一個文件中的這些事件(event.js)是這樣的:Backbone.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']'沒有被提取?

回答

3

考慮到這兩條線:

var events = function() { console.log("Data is "+this.data)}; 
events = _.bind(events,data); 

假設data在這一點上是一個Array(['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更多的例子。