骨干每个都未定义

Gre*_*ner 2 javascript jquery backbone.js

为什么在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);
});
Run Code Online (Sandbox Code Playgroud)

jsFiddle这里:http://jsfiddle.net/netroworx/KLYL9/

Bas*_*ter 10

将其更改为:

actionCollection.each(function(item) {
        alert(item);
});
Run Code Online (Sandbox Code Playgroud)

它工作正常.

这是因为actionCollection不是一个数组,所以_.each(collection)不起作用,而collection.each也不行,因为该函数是构建到Backbone集合中的.

话虽这么说,这也有效:

_.each(actionCollection.toJSON(), function(item) {
        alert(item);
});
Run Code Online (Sandbox Code Playgroud)

因为现在集合是一个实际的数组.