2013-07-01 44 views
2

爲什麼該變量在此Backbone示例中未定義?主幹每個未定義

var Action = Backbone.Model.extend({ 
defaults: { 
    "selected": false, 
    "name": "First Action", 
    "targetDate": "10-04-2014" 
} 
}); 

var Actions = Backbone.Collection.extend({ 
    model: Action 
}); 

var actionCollection = new Actions([new Action(), new Action(), new Action(), new Action()]); 

_.each(actionCollection, function(item) { 
    alert(item); 
}); 

的jsfiddle這裏:http://jsfiddle.net/netroworx/KLYL9/

回答

9

將其更改爲:

actionCollection.each(function(item) { 
     alert(item); 
}); 

,它工作正常。

這是因爲actionCollection不是數組,所以_.each(collection)不起作用,但collection.each會這樣做,因爲該函數被構建到Backbone集合中。

話雖這麼說,這也適用:

_.each(actionCollection.toJSON(), function(item) { 
     alert(item); 
}); 

因爲現在的集合是一個實際的數組。

0

_.each接受一個數組作爲第一個參數,但是您通過了一個Collection

只需使用Collection.each方法:

actionCollection.each(function(item){ 
    //do stuff with item 
});