再帰的なtoJSON()

http://www.shesek.info/web-development/recursive-backbone-models-tojson

Backbone.Model.prototype.toJSON = function() {
  if (this._isSerializing) {
    return this.id || this.cid;
  }
  this._isSerializing = true;
  var json = _.clone(this.attributes);
  _.each(json, function(value, name) {
    _.isFunction(value.toJSON) && (json[name] = value.toJSON());
  });
  this._isSerializing = false;
  return json;
};


var Dish = Backbone.Model.extend({});
var Dinner = Backbone.Collection.extend({
  model: Dish
});
var Ingredient = Backbone.Model.extend({});
var Ingredients = Backbone.Collection.extend({
  model: Ingredient
});

var dinner = new Dinner([{
  name: 'Green pepper steak',
  ingredients: new Ingredients([{
    name: 'Green pepper',
    amount: 2
  },
  {
    name: 'beef',
    amount: 4
  }])
},
{
  name: 'Rice',
  ingredients: new Ingredients([{
    name: 'Brown rice',
    amount: 8
  }])
}]);

console.log(dinner.toJSON());
console.log(JSON.stringify(dinner.toJSON()));