I am trying to implement some sort of nested collections in a Backbone.Model
To do this I have to overwrite the adapter functions which parse the server response and wrap the array into a collection and the function which serializes the whole object without any helper methods. I am having problems with the second one.
var Model = Backbone.Model.extend({
urlRoot: "/model",
idAttribute: "_id",
// this wraps the arrays in the server response into a backbone collection
parse: function(resp, xhr) {
$.each(resp, function(key, value) {
if (_.isArray(value)) {
resp[key] = new Backbone.Collection(value);
}
});
return resp;
},
// serializes the data without any helper methods
toJSON: function() {
// clone all attributes
var attributes = _.clone(this.attributes);
// go through each attribute
$.each(attributes, function(key, value) {
// check if we have some nested object with a toJSON method
if (_.has(value, 'toJSON')) {
// execute toJSON and overwrite the value in attributes
attributes[key] = value.toJSON();
}
});
return attributes;
}
});
The problem is now at the second part in toJSON. For some reason
_.has(value, 'toJSON') !== true
doesn't return true
Could somebody tell me what is going wrong?
Underscore's
has
does this:But your
value
won't have atoJSON
property sincetoJSON
comes from the prototype (see http://jsfiddle.net/ambiguous/x6577/).You should use
_(value.toJSON).isFunction()
instead: