1

在使用主干访问 api 时,我发现我只需要在响应中包含一些数据。除了关于我不需要的对象的数据之外,网络服务器还给我返回元数据。

以下解决方案有效,但感觉不对。有这样做的标准方法吗?

var accountsCollection = new AccountsCollection();

accountsCollection.fetch({success : function(collection){
    var results = new AccountsCollection();
    collection.each(function(item){
        results.add(new AccountModel({
            id: item.toJSON().result[0].id,
            messageText: item.toJSON().messageText,
            address1: item.toJSON().result[0].address1,
            address2: item.toJSON().result[0].address2
        }));
    });

    onDataHandler(results);
}});

编辑:这是我基于接受的答案的最终解决方案:

    parse: function(response) {
        var accounts = [];
        _.each(response['result'], function (account) {
            accounts.push(account);
        });
        return accounts;
    }
4

1 回答 1

4

您可以尝试覆盖该Backbone.Collection.parse方法并做一些疯狂的下划线操作。不知道它是否适合您的数据..

var keysILike = ['foo', 'bar'];

AccountsCollection.extend({
  parse: function(response) {
    return _.compact(_.flatten(_.map(response, function (model) {
      var tmp = {};
      _.each(_.keys(model), function (key) {
        if (_.contains(keysILike, key)) tmp[key] = model[key];
      })
      return tmp;
    })));
  }
});

关于@Sushanth 的出色表现,您肯定想使用此解决方案:

var keysILike = ['foo', 'bar'];

AccountsCollection.extend({
  parse: function(response) {
    _.each(response, function (model) {
      _.each(_.keys(model), function (key) {
        if (!_.contains(keysILike, key)) delete model[key]
      })
    });
    return response;
  }
});
于 2013-07-26T23:47:06.620 回答