假設你的數據結構看起來像這樣
[
{
title: "item 1",
nodes: [
{title: "item a",
nodes: [
{title: "item i"},
{title: "item ii"}
]
},
{title: "item b"
}
]
},
{
title: "item 2"
}
]
,你可以通過重寫你的模型的解析方法,建立層次結構:
var Node = Backbone.Model.extend({
parse: function(data) {
this.nodes = new Nodes(data.nodes, {parse: true});
return _.omit(data, 'nodes');
}
});
var Nodes = Backbone.Collection.extend({
model: Node
});
var c = new Nodes(data_structure, {parse: true});
// parse: true is only needed if you pass the data as an argument
Node.parse
提取從數據哈希nodes
財產在對象上構建一個自定義屬性,然後返回剩下的部分讓Backbone處理其他屬性。然後您使用model.nodes
訪問該集合。和小提琴一起玩http://jsfiddle.net/C8HGY/