Backbone - 嵌套在模型中的集合 [英] Backbone - Collections nested in Models

查看:19
本文介绍了Backbone - 嵌套在模型中的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在模型中嵌套集合?

Is it possible to nest collections within models?

我知道您可以在模型的初始化回调中创建新集合,并创建可以在集合和父模型之间来回传递的引用.但是是否可以将集合设置为模型的一部分,使其导出的 JSON 如下所示:

I know that you can create new collections in the initialize callback of a model, and create references that you can pass back and forth between the collection and parent model. But is it possible to set the collection as part of the model, such that the JSON it exports looks like this:

{
  blah: 'blah',
  myCollection: [
      {
         foo: 'asdf',
         bar: 'qwer'
      },
      {
         foo: 'asdf123',
         bar: 'qwer123'
      }
  ]
}

如果没有,您如何处理将具有相关集合的模型同步到后端?您是否必须利用主干的同步并重建 JSON 或者是否有更无缝的东西?

If not, how do you handle syncing a model with related collections to the backend? Do you have to tap into backbone's sync and rebuild the JSON or is there something more seamless?

抱歉,如果这个问题已经在别处得到解答.我环顾四周,看到了一些解决方法,但没有什么能真正满足我的需求.

Sorry if this question has been answered elsewhere. I've looked around and seen some workarounds, but nothing that really answers what I'm looking for.

推荐答案

有两种方法.第一个是定义一个获取一切的根模型.您覆盖它的 parse() 方法来为嵌套属性创建子集合和子模型,并覆盖 toJSON() 方法以转换回 JSON 结构,适合用于保存到服务器.

There are two approaches. The first is to define a root Model that gets everything. You override it's parse() method to create sub-collections and sub-models for nested attributes, and override the toJSON() method to convert back to the JSON structure, suitable for saving to the server.

这对于小型子集合来说是完全可以接受的.这需要一点编程,但如果你能读懂 Backbone 的源代码,那么怎么做应该是,嗯,不明显,但至少可以理解.

This is perfectly acceptable for small subcollections. It takes a bit of programming, but if you can read the Backbone source code, how to do it should be, well, not obvious, but at least understandable.

或者您可以使用 Backbone Relational,它为您完成所有工作.

Or you can use Backbone Relational, which does all the work for you.

这篇关于Backbone - 嵌套在模型中的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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