I see there are techniques available to have deep models in Backbone, but how about hierachical collections of a single model?
An obvious example is a category tree. So, we can have a category model which has a few properties, 'name', 'type', 'color', whatever.
Rather than have relational db style parent ids, we're using js so we want the data to be represented as json.
Can backbone be leveraged to support (presumably by augmenting collections) data structures that contain instances of a single model in a tree (such that the models and sub models are all instances of the same model)?
Have a look at Backbone-Relational or supermodel.js.
These projects provide better forms of model nesting than the default implementation.
We just nest Backbone models like:
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(); });
}
});
So the JSON representations look correct when we nest models. You'll have to pay attention to the parse
method on your model though - when you get back your JSON from the server you're going to have to generate all the submodels and collections there in order for it all to work correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With