2017-02-19 39 views
0

我希望有人可以指導我如何處理這個json數據結構。ExtJS 6 Rest代理其中JSON數據對象是ID

這裏有一個例子:(我有零控制這個數據的)

{ 
    "1": { 
     "name": "thing 01", 
     "attributes": { 
      "color": "red", 
      "brand": "ACME" 
     } 
    }, 
    "2": { 
     "name": "thing 02", 
     "attributes": { 
      "color": "blue", 
      "brand": "ACME" 
     } 
    } 
} 

所以我感到困惑如何使用reader

Ext.define('MyApp.model.Thing', { 
    extend: 'Ext.data.Model' 

    fields: [ 
     { name: 'name' }, 
     { name: 'attributes', type: 'auto' } 
    ], 

    proxy: { 
     type: 'rest', 
     url: 'http://example.com/api/things', 

     reader: { 
      type: 'json', 
      rootProperty: ??? // <--- How should this work? 
     } 
    } 
}); 

我已經得到了記錄想知道是否有辦法做類似...

rootProperty: '[id]' 

還有一種方法來指定t他是什麼時候是數據對象的ID?也許不知何故在模型上使用idProperty配置?

我應該使用reader.format方法嗎?這似乎有點毛...

任何想法是apreciated。謝謝!

+0

「rootProperty」配置用於設置所有數據的根目錄,而不是每個記錄。另外,我還沒有在ExtJS 6 [documentation](http://docs.sencha.com/extjs/6.2.0/)中找到'reader.format'方法。 – MarthyM

回答

2

您的確切問題已經回答here

您應該實施自定義閱讀器並覆蓋getResponseData方法。

Ext.define('MyReader', { 
    extend: 'Ext.data.reader.Json', 
    alias: 'reader.myreader', 

    getResponseData: function(response) { 
     var data = this.callParent([response]); 

     //do stuff here 

     return data; 
    } 
}); 
+0

啊謝謝你!不知何故,我從來沒有在Sencha論壇上發現過。這將有助於一堆! – Trozdol

5

編寫自定義讀取器類:

Ext.define('MyReader', { 
    extend: 'Ext.data.reader.Json', 
    alias: 'reader.myreader', 

    config: { 
     transform: function (data) { 
      var ret = [], 
       key, o; 

      for (key in data) { 
       o = data[key]; 
       o.id = key; 
       ret.push(o); 
      } 

      return ret; 
     } 
    } 
}); 

Ext.define('Thing', { 
    extend: 'Ext.data.Model', 

    fields: ['name', 'attribute'], 

    proxy: { 
     type: 'ajax', 
     url: 'data1.json', 

     reader: { 
      type: 'myreader' 
     } 
    } 
}); 

fiddle