Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Backbones toJSON function include sub-models and collections?

Tags:

backbone.js

I have a few models that don't just contain basic data attributes, but they might have one or two attributes that hold another models object.

This has been okay, but now I want to call

myRootModel.toJSON()

and I've noticed that it doesn't call .toJSON on the other models in my model that I'm trying to call toJSON() on.

Is there a way to override backbone model .toJSON to go through all fields, recursively, whether they are basic attributes, sub-models or collections? If not, can I override toJSON in each model / collection?

I'm aware of backbone-relational, but I don't want to go that route - I'm not using fetch/save, instead our API returns responses that I adjust in the models parse function and simply invoke new MyRootModel(data,{parse:true}).

like image 630
Devology Ltd Avatar asked Jun 11 '13 17:06

Devology Ltd


1 Answers

Here's a way you can achieve such a thing (there's maybe another way):

Backbone.Model.prototype.toJSON = function() {
  var json = _.clone(this.attributes);
  for(var attr in json) {
    if((json[attr] instanceof Backbone.Model) || (json[attr] instanceof Backbone.Collection)) {
      json[attr] = json[attr].toJSON();   
    }
  }
  return json;
};

http://jsfiddle.net/2Asjc/.

like image 101
Loamhoof Avatar answered Sep 27 '22 21:09

Loamhoof