0

I have a model which keeps some other models in an attribute array. When these models are stored, however, I don't want to keep the sub-modules around--instead, I want to store the primary keys, and then when the model is fetched from the server, its parse will "reconstitute" them by fetching the related models.

What is the best approach to accomplishing this? The closest I've come to getting it to work is overriding the sync method:

sync : function(method, model, options) {
  var topics = this.get('topics');
  model.attributes.topics = _.pluck(topics, 'id');

  var ret = Backbone.Model.prototype.sync.call(this, method, model, options);

  this.attributes.topics = topics;

  return ret;
},

but this regularly fails, leaving the keys in the attributes instead of the full models & consequently crashing.

Parse function (slightly paraphrased):

parse : function(response) {
  response.topics = _.map(response.topics, function(item) {
    return app.topics.getByPK(item);
  }
  return response;
}
4

1 回答 1

1

我会做的更多的是沿着这些思路:

parse : function(response) {
  this.topics = _.map(response.topics, function(item) {
    return app.topics.getByPK(item);
  }
  return response;
}

这使您的 id 数组始终保持完整,并且您可以通过使用this.topics而不是this.get('topics')或访问this.attributes.topics

于 2013-08-09T19:15:33.883 回答