Loading TreeStore with JSON that has different children fields

前端 未结 1 448
被撕碎了的回忆
被撕碎了的回忆 2021-01-07 10:58

I am having a JSON data like below.

{
    \"divisions\": [{
        \"name\": \"division1\",
        \"id\": \"div1\",
        \"subdivisions\": [{
                  


        
相关标签:
1条回答
  • 2021-01-07 11:22

    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.

    0 讨论(0)
提交回复
热议问题