[英]How do I get a subset of a Backbone.Collection?
鑒於此系列 -
{"education":
[
{
"school":{
"name":"Maxwell",
"type":"Secondary",
"teachers": [
{"name":"Mrs. Smith","subject":"Chemistry"},
{"name":"Mr. Jones","subject":"Calculus"}
]
}
},{
"school":{
"name":"Bright",
"type":"Elementry",
"teachers": [
{"name":"Mr. Anthony","subject":"Reading"},
{"name":"Mrs. Bates","subject":"Social Studies"}
]
}
}
]
}
我正在嘗試返回所有學校項目,以便我可以在模板中顯示名稱。
鑒於此代碼 -
schools = [];
filtered = this.filter(function (item) {
return (
item.get('school') !== ''
)
});
_.each(filtered, function(k,v) {
_.each(k.attributes.models, function (k2, v2) {
schools.push(k2.get('school'));
});
});
colSchools = new Backbone.Collection(schools);
這可以完成工作,但它似乎不是非常有效,或者確實是正確的做事方式。
instead of filtered, and I get an error that . 我嘗試循環而不是過濾,我得到一個錯誤, 。 and what am I missing about grabbing the subset of the education collection? 我想我的問題是兩個部分 - 為什么返回 ,我對於抓住教育集合的子集有什么看法? 我覺得嵌套循環是多余的工作,不需要開心。 可能是我誤解了Backbone如何處理集合,還是這真的是實現目標的最佳方式?
我認為http://backbonejs.org/#Collection-pluck正是你要找的:
var stooges = new Backbone.Collection([
{name: "Curly", age: 60},
{name: "Larry", age: 70},
{name: "Moe", age: 80}
]);
var names = stooges.pluck("name");
alert(JSON.stringify(names));
如果你試試這個應警告["Curly","Larry","Moe"]
編輯:對不起我沒有發現嵌套級別,但是因為它只是一個地圖應用程序你可以這樣做:
stooges.map(function(model){
return model.get('school').name;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.