backbone.js: nadpisywanie toJSON
Próbuję zaimplementować pewnego rodzaju zagnieżdżone kolekcje w modelu Backbone.Model
Aby to zrobić, muszę nadpisać funkcje adaptera, które analizują odpowiedź serwera i opakować tablicę w kolekcję oraz funkcję, która serializuje cały obiekt bez żadnych metod pomocniczych. Mam problemy z drugim.
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;
}
});
Problem jest teraz w drugiej części toJSON. Z jakiegoś powodu
_.has(value, 'toJSON') !== true
nie zwraca prawdy
Czy ktoś mógłby mi powiedzieć, co się dzieje?