来自JSON的EXTJS 5.1非常简单的TreeStore

时间:2015-03-02 09:26:21

标签: extjs tree store extjs5

我环顾四周但仍然不明白如何正确创建树库。 我从服务器获得了这个非常简单的json:

{
  "Results": [
    {
      "name": "John",
      "age": 23,
      "cars": [
        {
          "name": "Clio",
          "brand": "Renault"
        },
        {
          "name": "Class S",
          "brand": "Mercedes"
        }
      ]
    },
    {
      "name": "Michel",
      "age": 42,
      "cars": [
        {
          "name": "Qashqai",
          "brand": "Nissan"
        }
      ]
    }
  ]
}

我有两个模特:

Ext.define('Person', {
    extend: 'Ext.data.Model',
    fields: [ 'name', 'age']
});

Ext.define('Car', {
    extend: 'Ext.data.Model',
    fields: [ 'name', 'brand']
});

现在我知道我必须创建一个树存储,但在我看到的所有示例中,json中总有一个“children”属性,我没有。

如何使用以下json创建树存储?

提前多多感谢:) !!

1 个答案:

答案 0 :(得分:2)

您始终可以为数据构建正确的格式化对象,如下所示:

Ext.application({
    name: 'Fiddle',

    launch: function () {

        var myTreeData = {
                "Results": [{
                    "name": "John",
                    "age": 23,
                    "cars": [{
                        "name": "Clio",
                        "brand": "Renault"
                    }, {
                        "name": "Class S",
                        "brand": "Mercedes"
                    }]
                }, {
                    "name": "Michel",
                    "age": 42,
                    "cars": [{
                        "name": "Qashqai",
                        "brand": "Nissan"
                    }]
                }]
            },
            modifiedData = {
                expanded: true,
                children: []
            };
        myTreeData.Results.forEach(function (result) {
            var newChildrenArray = [];
            result.cars.forEach(function (car) {
                var newChild = {
                    text: car.name,
                    leaf: true
                };
                newChildrenArray.push(newChild);
            });
            var person = {
                text: result.name,
                leaf: (newChildrenArray.length > 0 ? false : true),
                children: newChildrenArray
            };
            modifiedData.children.push(person);
        });

        var store = Ext.create('Ext.data.TreeStore', {
            root: modifiedData
        });

        Ext.create('Ext.tree.Panel', {
            title: 'Simple Tree',
            width: 200,
            height: 150,
            store: store,
            rootVisible: false,
            renderTo: Ext.getBody()
        });
    }
});

在这里演示:https://fiddle.sencha.com/#fiddle/j05