I've got the following JSON provided from a server. With this, I want to create a model with a nested model. I am unsure of which is the way to achieve this.
//json
[{
name : "example",
layout : {
x : 100,
y : 100,
}
}]
I want these to be converted to two nested backbone models with the following structure:
// structure
Image
Layout
...
So I define the Layout model like so:
var Layout = Backbone.Model.extend({});
But which of the two (if any) techniques below should I use to define the Image model? A or B below?
A
var Image = Backbone.Model.extend({
initialize: function() {
this.set({ 'layout' : new Layout(this.get('layout')) })
}
});
or, B
var Image = Backbone.Model.extend({
initialize: function() {
this.layout = new Layout( this.get('layout') );
}
});
I use Backbone DeepModel plugin for nested models and attributes.
https://github.com/powmedia/backbone-deep-model
You can bind to change events 'n levels deep. for example:
model.on('change:example.nestedmodel.attribute', this.myFunction);
Use backbone-forms
It supports nested forms, models and toJSON. ALL NESTED
If you don't want to add yet another framework, you might consider creating a base class with overridden
set
andtoJSON
and use it like this:You'll need
BaseModel
from this answer (available, if you fancy, as a gist).I realize I'm late to this party, but we recently released a plugin to deal with exactly this scenario. It's called backbone-nestify.
So your nested model remains unchanged:
var Layout = Backbone.Model.extend({...});
Then use the plugin when defining the containing model (using Underscore.extend):
After that, assuming you have a model
m
which is an instance ofImage
, and you've set the JSON from the question onm
, you can do:I'm not sure Backbone itself has a recommended way to do this. Does the Layout object have its own ID and record in the back end database? If so you can make it its own Model as you have. If not, you can just leave it as a nested document, just make sure you convert it to and from JSON properly in the
save
andparse
methods. If you do end up taking an approach like this, I think your A example is more consistent with backbone sinceset
will properly updateattributes
, but again I'm not sure what Backbone does with nested models by default. It's likely you'll need some custom code to handle this.CoffeeScript version of rycfung's beautiful answer:
Ain't that sweet? ;)