Loading TreeStore with JSON that has different children fields

喜你入骨 提交于 2019-11-30 20:54:11

问题


I am having a JSON data like below.

{
    "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"
            }]
        }

        ]
    }]
}

I want to read this into a TreeStore, but cannot change the subfields ( divisions, subdivisions, schemes ) to be the same (eg, children).

How can achieve I this?


回答1:


When nested JSON is loaded into a TreeStore, essentially the children nodes are loaded through a recursive calls between TreeStore.fillNode() method and NodeInterface.appendChild().

The actual retrieval of each node's children field is done within TreeStore.onNodeAdded() on this line:

dataRoot = reader.getRoot(data);

The getRoot() of the reader is dynamically created in the reader's buildExtractors() method, which is what you'll need to override in order to deal with varying children fields within nested JSON. Here is how it's done:

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' ];
        };
    }
});

This will be able to interpret such 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
            }
         ]
      }
   ]
}

See this JsFiddle for fully working code.



来源:https://stackoverflow.com/questions/12092123/loading-treestore-with-json-that-has-different-children-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!