gpt4 book ai didi

javascript - 表示树数据的 Backbone 集合

转载 作者:行者123 更新时间:2023-12-02 22:22:25 27 4
gpt4 key购买 nike

我想将 json 数据以树的形式加载到 Backbone Collection 中。我不能这样做。谁能解释一下我做错了什么?

我的非常简单的模型:

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

我的负载尝试:

    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"

希望这就是您所追求的。

关于javascript - 表示树数据的 Backbone 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6026752/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com