问题描述
我有没有只包含基本的数据属性少数机型,但他们可能有另一个持有对象模型的一个或两个属性。
I have a few models that don't just contain basic data attributes, but they might have one or two attributes that hold another models object.
这已经好了,但现在我想打电话给
This has been okay, but now I want to call
myRootModel.toJSON()
myRootModel.toJSON()
和我注意到,它不叫.toJSON在我的模型中的其他车型,我试图在调用的toJSON()。
and I've noticed that it doesn't call .toJSON on the other models in my model that I'm trying to call toJSON() on.
有没有办法覆盖骨干模型.toJSON要经过所有领域,递归后,无论是基本属性,子模型或集合?如果没有,我可以覆盖的toJSON每一个模型/收集?
Is there a way to override backbone model .toJSON to go through all fields, recursively, whether they are basic attributes, sub-models or collections? If not, can I override toJSON in each model / collection?
我知道骨干关系,但我不希望走这条路 - 我不使用获取/保存,而不是我们的API返回,我在模型解析功能调整和简单地调用新MyRootModel回应(数据,解析{:真})。
I'm aware of backbone-relational, but I don't want to go that route - I'm not using fetch/save, instead our API returns responses that I adjust in the models parse function and simply invoke new MyRootModel(data,{parse:true}).
推荐答案
这里有一个方法可以实现这样的事情(有可能另一种方法):
Here's a way you can achieve such a thing (there's maybe another way):
Backbone.Model.prototype.toJSON = function() {
var json = _.clone(this.attributes);
for(var attr in json) {
if((json[attr] instanceof Backbone.Model) || (json[attr] instanceof Backbone.Collection)) {
json[attr] = json[attr].toJSON();
}
}
return json;
};
。
这篇关于如何使骨干网的toJSON功能包括子模型和集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!