我想以树的形式将JSON数据加载到Backbone Collection中。我做不到谁能解释我在做什么错?

我非常简单的模型:

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

而我的负荷attepmt:
    var treeJs =
        [
            { id: "tvRoot", title: 'Root', cssClass: 'root',
                items: [
                    { id: "ti1", title: 'Item1', cssClass: 'item',
                        items: [
                            { id: "ti11", title: 'SubItem11', cssClass: 'subitem'},
                            { id: "ti12", title: 'SubItem12', cssClass: 'subitem'}]},
                    { id: "ti2", title: 'Item2', cssClass: 'item',},
                    { id: "ti3", title: 'Item3', cssClass: 'item',
                        items: [
                            { id: "ti31", title: 'SubItem31', cssClass: 'subitem'},
                            { id: "ti32", title: 'SubItem32', cssClass: 'subitem'},
                            { id: "ti33", title: 'SubItem33', cssClass: 'subitem'}]}]
        }];
    this.TreeData = new CTreeDataItems();
    this.TreeData.add(treeJs);

最佳答案

尝试用Model作为节点表示树,每个节点包含其子节点的Collection:

var CTreeDataItem = Backbone.Model.extend({
    initialize: function() {
        if (Array.isArray(this.get('items'))) {
            this.set({items: new CTreeDataItemChildren(this.get('items'))});
        }
    }
});

// children collection
var CTreeDataItemChildren = Backbone.Collection.extend({
    model: CTreeDataItem
});

// create
var treeData = new CTreeDataItemChildren(treeJs);

// access
treeData.at(0).get('items').at(1).get('title')
// returns "Item2"

编辑2011-05-18:如果要展平树并维护对树中每个节点的父级的引用:
// flatten the tree outside of Backbone. Alternatively,
// you could override the constructor of the CTree collection
// to provide encapsulation
function flatten(parentID, arr) {
    var out = [];
    for (var i = 0; i < arr.length; i++) {
        var node = arr[i];
        node.parentID = parentID;
        out.push(node);
        if (Array.isArray(node.items))
            Array.prototype.push.apply(out, flatten(node.id, node.items));
        delete node.items;
    }
    return out;
}

// remove above code that would have provided nesting
var CTreeDataItem = Backbone.Model.extend({});

// children collection, as before
var CTreeDataItemCollection = Backbone.Collection.extend({
    model: CTreeDataItem
});

// create
var treeData = new CTreeDataItemChildren(flatten('', treeJs));

// as before, but now there's the 'parentID' FK
treeData.at(3).get('parentID')
// returns "ti1"

希望那是你的追求。

09-21 00:05