问题
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?
回答1:
Underscore's has does this:
has
_.has(object, key)
Does the object contain the given key? Identical to
object.hasOwnProperty(key)
, but uses a safe reference to thehasOwnProperty
function, in case it's been overridden accidentally.
But your value
won't have a toJSON
property since toJSON
comes from the prototype (see http://jsfiddle.net/ambiguous/x6577/).
You should use _(value.toJSON).isFunction()
instead:
if(_(value.toJSON).isFunction()) {
// execute toJSON and overwrite the value in attributes
attributes[key] = value.toJSON();
}
来源:https://stackoverflow.com/questions/11958747/backbone-js-overwritting-tojson