-
Notifications
You must be signed in to change notification settings - Fork 1
Converting nested JSON data into models or collections
crwang edited this page Apr 13, 2015
·
1 revision
Sometimes we will have nested data coming back from the API and we will want to parse the nested data into models or collections so that it can be used properly in the underlying view structure.
Rendr allows this by overriding the parse method on the model.
Below is an example of a products array nested inside a department object.:
templates/department/show.hbs
{{view "products/list" collection=products }}
models/department.js
parse: function(data) {
if (_.isArray(data.featuredProducts)) {
data.products = this.app.modelUtils.getCollection('Products', data.featuredProducts, {
app: this.app,
params: {
departmentId: data.id,
type: 'featured'
}
});
}
return data;
}
Also, note that we are using _.isArray
to determine if it's an array for our collection. This is important because if the data was coming back as products
then we would want to overwrite the result to be our collection. If we don't use isArray the data gets messed up. ie.:
parse: function(data) {
if (_.isArray(data.products)) {
data.products = this.app.modelUtils.getCollection('Products', data.products, {
app: this.app,
params: {
departmentId: data.id,
type: 'normal'
}
});
}
return data;
}