2

新的 Backbone 和下划线 js 在这里。

我有一个要转换为模型集合的数组数组。

所以就像

{ {1, 2, 3, 4}, {5, 6, 7, 8}}

第二级数组是主干模型的内容。现在,我有

collection.reset(_.map(results, (indvidualResults) -> new model(individualResults))

当我执行 console.log(collection.pop) 时,这不起作用,我打印出一个函数。我认为这是因为我正在使用一组数组(但我可能是错的)。如何将第二个数组转换为模型,然后将其放入集合中?

4

1 回答 1

9

Reshape your raw data to look more like:

[{ first: 1, second: 2, third: 3, fourth: 4 }, { first: 5, second: 6, third: 7, fourth: 8}]

Assuming you have a model and collection defined something like:

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

Then just pass the array of attribute hashes into the reset method:

var results = [{ first: 1, second: 2, third: 3, fourth: 4 }, { first: 5, second: 6, third: 7, fourth: 8}];
var collection = new Collection();
collection.reset(results);
var model = collection.pop();
console.log(JSON.stringify(model.toJSON());
于 2012-07-14T01:30:48.133 回答