futuraprime
futuraprime

Reputation: 5578

Backbone.js parse for saving

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;
}

Upvotes: 0

Views: 80

Answers (1)

kalley
kalley

Reputation: 18462

What I would do would be something more along these lines:

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

Which keeps your array of ids intact at all times, and you have access by using this.topics instead of this.get('topics') or this.attributes.topics

Upvotes: 1

Related Questions