【问题标题】:Converting Array of Arrays to Backbone Collection of Models将数组数组转换为模型的主干集合
【发布时间】:2012-07-13 21:46:35
【问题描述】:

Backbone 的新手并在此处下划线 js。

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

原来如此

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

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

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

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

【问题讨论】:

  • (1) 您的数据到底是什么样的? (2) 当Collection#reset 会为你做这一切时,你为什么要做_.map? (3) 集合有一个pop method 所以当然console.log(collection.pop) 给你一个功能。
  • 你的意思是console.log(collection.pop())console.log(collection.pop)*应该*给你一个函数。

标签: collections backbone.js coffeescript models


【解决方案1】:

重塑您的原始数据,使其看起来更像:

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

假设您有一个模型和集合定义如下:

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

然后只需将属性哈希数组传递给 reset 方法:

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());

【讨论】:

  • collection.reset(results); 工作正常。但看起来它没有在每个模型上执行 .parse() 方法。
猜你喜欢
  • 2013-01-04
  • 2015-01-20
  • 2021-04-20
  • 1970-01-01
  • 2011-09-18
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 2016-05-12
相关资源
最近更新 更多