Many of my Backbone models often deal with nested models and collections, so far I\'m using a combination of defaults
, parse
and toJSON
ma
Faced with the same problem, I do something like that (the code below is output of TypeScript compiler so it's a bit verbose):
var Model = (function (_super) {
__extends(Model, _super);
function Model() {
_super.apply(this, arguments);
}
Model.prototype.fieldToType = function () {
return {};
};
Model.prototype.parse = function (response, options) {
_.each(this.fieldToType(), function (type, field) {
if (response[field]) {
if (_.isArray(response[field])) {
response[field] = _.map(response[field], function (value) {
return new type(value, { parse: true });
});
} else {
response[field] = new type(response[field], { parse: true });
}
}
});
return _super.prototype.parse.call(this, response, options);
};
Model.prototype.toJSON = function () {
var j = _super.prototype.toJSON.call(this);
_.each(this.fieldToType(), function (type, field) {
if (j[field]) {
if (_.isArray(j[field])) {
j[field] = _.map(j[field], function (value) {
return value.toJSON();
});
} else {
j[field] = j[field].toJSON();
}
}
});
return j;
};
return Model;
})(Backbone.Model);
And then I can simply override the fieldToType method to define types of my fields:
PendingAssignmentOffer.prototype.fieldToType = function () {
return {
'creator': User,
'task_templates': TaskTemplateModel,
'users': User,
'school_classes': SchoolClass
};
};