1

我的 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

此外,如果您觉得以不同的方式这样做会更好,我愿意接受建议。

4

0 回答 0