骨干每个都未定义

时间:2013-07-01 09:29:45

标签: 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);
});

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

2 个答案:

答案 0 :(得分:10)

将其更改为:

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

它工作正常。

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

话虽如此,这也有效:

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

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

答案 1 :(得分:0)

_.each接受数组作为第一个参数,但您传递了Collection

只需使用Collection.each方法:

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