使用具有不同子字段的JSON加载TreeStore

时间:2012-08-23 12:57:39

标签: json extjs extjs4.1

我正在使用如下的JSON数据。

{
    "divisions": [{
        "name": "division1",
        "id": "div1",
        "subdivisions": [{
            "name": "Sub1Div1",
            "id": "div1sub1",
            "schemes": [{
                "name": "Scheme1",
                "id": "scheme1"
            }, {
                "name": "Scheme2",
                "id": "scheme2"
            }]
        }, {
            "name": "Sub2Div1",
            "id": "div1sub2",
            "schemes": [{
                "name": "Scheme3",
                "id": "scheme3"
            }]
        }

        ]
    }]
}

我想将其读入TreeStore,但无法将子字段(divisionssubdivisionsschemes)更改为相同(例如children)。

如何实现这个目标?

1 个答案:

答案 0 :(得分:7)

当嵌套的JSON加载到TreeStore中时,基本上通过TreeStore.fillNode()方法和NodeInterface.appendChild()之间的递归调用加载子节点。

每个节点的子字段的实际检索在此行的TreeStore.onNodeAdded()内完成:

dataRoot = reader.getRoot(data);

阅读器的getRoot()是在阅读器的buildExtractors()方法中动态创建的,为了处理嵌套JSON中不同的子字段,您需要覆盖该方法。以下是它的完成方式:

Ext.define('MyVariJsonReader', {
    extend: 'Ext.data.reader.Json',
    alias : 'reader.varijson',

    buildExtractors : function()
    {
        var me = this;    
        me.callParent(arguments);

        me.getRoot = function ( aObj ) {                
            // Special cases
            switch( aObj.name )
            {
                case 'Bill':   return aObj[ 'children' ];
                case 'Norman': return aObj[ 'sons' ];                    
            }

            // Default root is `people`
            return aObj[ 'people' ];
        };
    }
});

这将能够解释这样的JSON:

{
   "people":[
      {
         "name":"Bill",
         "expanded":true,
         "children":[
            {
               "name":"Kate",
               "leaf":true
            },
            {
               "name":"John",
               "leaf":true
            }
         ]
      },
      {
         "name":"Norman",
         "expanded":true,
         "sons":[
            {
               "name":"Mike",
               "leaf":true
            },
            {
               "name":"Harry",
               "leaf":true
            }
         ]
      }
   ]
}

有关完整的代码,请参阅this JsFiddle