Take a look at Backbone-Relational or supermodel.js .
These projects provide better forms of nesting than the default implementation.
We simply embed Backbone models, for example:
var MyModel = Backbone.Model.extend({}); var MySubModel = Backbone.Model.extend({}); var model = new MyModel({submodel: new MySubModel({color: 'blue'})});
And we override the toJSON
methods:
// nested models! Might just override the internal representation of this... _.extend(Backbone.Model.prototype, { // Version of toJSON that traverses nested models toJSON: function() { var obj = _.clone(this.attributes); _.each(_.keys(obj), function(key) { if(!_.isUndefined(obj[key]) && !_.isNull(obj[key]) && _.isFunction(obj[key].toJSON)) { obj[key] = obj[key].toJSON(); } }); return obj; } }); _.extend(Backbone.Collection.prototype, { // Version of toJSON that traverses nested models toJSON: function() { return this.map(function(model){ return model.toJSON(); }); } });
That way, JSON views look right when we insert models. You will need to pay attention to the parse
method on your model, although - when you return your JSON from the server, you will have to create all the submodels and collections there so that everything works correctly.
tkone source share