Recursive Backbone.Model’s toJSON()

Posted: July 18th, 2011 | Author: | Filed under: Javascript, Web Development | Tags: , , , , | 2 Comments »

If you’re using collections and models as attributes for other models, calling toJSON() on Backbone.Model objects isn’t very useful as it returns the models and collections as-is. I’ve opened an issue requesting to make it recursive, but it seems like its not going to be added.

If anyone still wants this functionality, you can use that modified version of Backbone.Model.prototype.toJSON that I added to the issue:

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

2 Comments on “Recursive Backbone.Model’s toJSON()”

  1. 1 Tyson Cadenhead said at 9:17 pm on April 16th, 2012:

    That worked perfectly. I only had to make one change because your example was using obj[name] instead of json[name], so I was getting an error because obj was undefined.

  2. 2 shesek said at 10:21 am on June 20th, 2012:

    @Tyson Ah, right. I had the same typo on the GitHub issue too. Fixed it here too, thanks


Leave a Reply