Skip to content

Instantly share code, notes, and snippets.

@imyelo
Last active August 29, 2015 14:08
Show Gist options
  • Save imyelo/9f7b81e5a78471999c44 to your computer and use it in GitHub Desktop.
Save imyelo/9f7b81e5a78471999c44 to your computer and use it in GitHub Desktop.
Better Backbone.Model/Collection.toJSON
Backbone.Model.prototype.toJSON = function () {
var result = {};
_.each(this.attributes, function (val, key) {
if (typeof val === 'undefined') {
result[key] = val;
} else if (typeof val.toJSON === 'function') {
result[key] = val.toJSON();
} else if (!_.isObject(val)) {
result[key] = val;
} else {
result[key] = _.isArray(val) ? val.slice() : _.extend({}, val);
}
});
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment