【问题标题】:Loading TreeStore with JSON that has different children fields使用具有不同子字段的 JSON 加载 TreeStore
【发布时间】:2012-08-23 12:57:38
【问题描述】:

我有如下 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)。

我怎样才能做到这一点?

【问题讨论】:

    标签: json extjs extjs4.1


    【解决方案1】:

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

    每个节点的children字段的实际检索在这一行的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 了解完整的工作代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      相关资源
      最近更新 更多