如何让 Backbones toJSON 函数包含子模型和集合? [英] How to make Backbones toJSON function include sub-models and collections?

查看:20
本文介绍了如何让 Backbones toJSON 函数包含子模型和集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些模型不仅包含基本数据属性,而且它们可能有一个或两个属性包含另一个模型对象.

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(数据,{parse:true}).

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;
};

http://jsfiddle.net/2Asjc/.

这篇关于如何让 Backbones toJSON 函数包含子模型和集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆