Ember-Model:从多个嵌套JSON级别序列化数据

时间:2014-08-20 16:52:38

标签: ember.js ember-model

我的JSON结构如下:

{
  "status": "success",
  "data": {
    "debtors": [
      {
        "debtor_id": 1048,
        "debtor_contact_id": 1086,
        ...
        ...
      },
      {
        "debtor_id": 1049,
        "debtor_contact_id": 1087,
        ...
        ...
      }
    ],
    "count": 2,
    "total": 475,
    "current_page": 1,
    "total_pages": 238,
    "page_size": 2
  }
}

我有一个自定义的Ember-Model适配器,一位同事朋友帮我写了一个允许我从debtors键中取出一个集合,如下所示:

var get = Ember.get;

var ViewAdapter = Ember.RESTAdapter.extend({
    buildURL: function(klass, id) {
        var urlRoot = Ember.get(klass, 'url');
        if (!urlRoot) { throw new Error('ViewAdapter requires a `url` property to be specified'); }
        if (!Ember.isEmpty(id)) {
            return urlRoot + "/" + id;
        } else {
            return urlRoot;
        }
    },
    ajaxSettings: function(url, method) {
        return {
            url: url,
            type: method,
            headers: {
                "Accept": "application/json; version=1.0.0"
            },
            dataType: "json"
        };
    },
    didFindQuery: function(klass, records, params, data) {
        var collectionKey = get(klass, 'collectionKey'),
            dataToLoad = collectionKey ? data['data'][collectionKey] : data;

        records.load(klass, dataToLoad);
    },
    didFindAll: function(klass, records, data) {
        var collectionKey = get(klass, 'collectionKey'),
            dataToLoad = collectionKey ? data['data'][collectionKey] : data;

        records.load(klass, dataToLoad);
    }
});

export default ViewAdapter;

在JSON中还有一些分页属性在data级别上,我想进入与债务人进入的模型相同的模型。

这就是我希望模型看起来像:

import ViewAdapter from '../../adapters/accounts/view';

var attr = Ember.attr;

var View = Ember.Model.extend({
    debtor_id:                      attr(),
    debtor_contact_id:              attr(),
    ...
    ...
    current_page:                   attr(),
    total_pages:                    attr()
});

View.adapter = ViewAdapter.create();
View.url =              'api/rest/debtor/list';
View.rootKey =          'data';
View.collectionKey =    'debtors';
View.primaryKey =       'debtor_id';

export default View;

如何更改此适配器以在data级别进入debtors级别之前获取这些属性?

此外,如果您认为以不同的方式做到这一点会更好,我愿意接受建议。

0 个答案:

没有答案