2
//A backbone model
var RequestModel = Backbone.Model.extend({});

//A backbone model
var ResponseModel = Backbone.Model.extend({});

RequestModel.save({
    success: function (ResponseModel ) {
        alert(ResponseModel .toJSON());
    }
})

Can i have a separate Model for Request and Response, as both Request and Response does not match. Its a total RPC call and not a CRUD operation.

4

1 回答 1

4

我以前也考虑过同样的问题,我觉得在 Backbone 中没有很好的方法来实现这一点。我想出的最好的方法是在模型上实现一个fromResponseandtoRequest方法,并覆盖model.parse并将model.sync模型对象映射到它们。就像是:

var Model = Backbone.Model.extend({
  fromResponse: function(responseAttrs) {
    var modelAttrs = {}; //map response attributes to modelAttrs
    return modelAttrs;
  },

  toRequest: function() {
    //map model attributes to response attributes here
    var modelAttrs = this.toJSON();
    var responseAttrs = {}; //map models attributes to requestAttrs
    return responseAttrs;
  },

  parse: function(response) {
    return this.fromResponse(response);
  },

  sync: function(method, model, options) { 
    options = options || {};
    options.data = this.toRequest();
    Backbone.sync(method, model, options);
  }
});

如果parseandsync在某种基类中被覆盖,那么您只需要为每个模型实现fromResponseand映射器。toRequest

另一种选择是Backbone.sync完全覆盖,并将每种类型映射Model到某种类型ModelRequestMapperModelResponseMapper对象以(反)序列化每个模型。我觉得这会更复杂,但如果你有很多模型,可能会更好地扩展。

/代码示例未测试

于 2013-02-04T21:31:58.027 回答