Loading TreeStore with JSON that has different children fields

坚强是说给别人听的谎言 提交于 2019-12-01 01:16:53

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.

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