Backbone.js的:overwritting的toJSON [英] backbone.js: overwritting toJSON
问题描述
我想实现某种嵌套集合在Backbone.Model
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;
}
});
现在的问题是在的toJSON的第二部分。
出于某种原因,
The problem is now at the second part in toJSON. For some reason
_.has(value, 'toJSON') !== true
没有返回true
doesn't return true
有人能告诉我是怎么回事了?
Could somebody tell me what is going wrong?
推荐答案
下划线的的
做到这一点:
Underscore's has
does this:
有 _。有(对象键)
是否包含对象给出的关键字?和 object.hasOwnProperty(键)
,但使用安全参考的hasOwnProperty
功能,以防它被覆盖意外。
Does the object contain the given key? Identical to object.hasOwnProperty(key)
, but uses a safe reference to the hasOwnProperty
function, in case it's been overridden accidentally.
但是,你的值
不会,因为的toJSON $一个
的toJSON
属性C $ C>来自原型(见 http://jsfiddle.net/ambiguous/x6577/ )。
But your value
won't have a toJSON
property since toJSON
comes from the prototype (see http://jsfiddle.net/ambiguous/x6577/).
您应该使用 _(value.toJSON).isFunction()
而不是:
if(_(value.toJSON).isFunction()) {
// execute toJSON and overwrite the value in attributes
attributes[key] = value.toJSON();
}
这篇关于Backbone.js的:overwritting的toJSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!