2012-07-13 82 views
2

新的Backbone和下劃線js在這裏。我有一個數組,我想要轉換爲模型集合的數組。將數組陣列轉換爲骨幹模型集合

所以它就像

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

陣列的第二個層次是發生了什麼事情到骨幹模型。現在,我有

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

這不工作,因爲當我做一個console.log(collection.pop)我得到一個功能打印出來。我認爲這是因爲我正在處理一組數組(但我可能是錯的)。如何將第二個數組轉換爲模型,然後將其放入集合中?

+0

(1)您的數據真的是什麼樣子? (2)爲什麼當['Collection#reset'](http://backbonejs.org/#Collection-reset)會爲你做所有這些時候'_.map'? (3)集合有一個['pop'方法](http://backbonejs.org/#Collection-pop),所以當然'console.log(collection.pop)'給你一個函數。 – 2012-07-13 22:44:17

+0

你的意思是'console.log(collection.pop())'? 'console.log(collection.pop)'*應該*給你一個函數。 – 2012-07-14 23:20:17

回答

9

重塑你的原始數據看起來更像:

[{ 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 
}); 

然後,只需通過屬性的陣列散列到復位方法:

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

** collection.reset(results); **正常工作。但看起來它不會在每個模型上執行.parse()方法。 – 2014-11-13 08:42:37