主干 - 嵌套在模型收藏 [英] Backbone - Collections nested in Models

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

问题描述

是否有可能巢收藏模型中?

我知道,你可以在模型的初始化回调创建新的集合,并创建可以来回传递收集和父模型之间的引用。但是,它可以设置集合作为模型的一部分​​,使得它JSON出口看起来是这样的:

  {
  胡说:'胡说',
  MyCollection的:
      {
         富:ASDF,
         巴:QWER
      },
      {
         富:asdf123',
         巴:qwer123
      }
  ]
}

如果没有,你是如何处理同步与相关收藏到后端的模式?你有进军骨干网的同步和重建JSON或者是有什么更完美的?

很抱歉,如果这个问题已在别处回答。我环顾四周,看到一些解决方法,但没有真正回答我要找的。

解决方案

有两种方法。第一种方法是定义一个根模型,获取的一切。你重写它的解析()方法来创建子集和子模型嵌套的属性,并重写的toJSON()方法来转换回JSON结构,适合保存到服务器上。

这是对小的子集合完全可以接受的。这需要一点编程的,但如果你可以阅读骨干源$ C ​​$ C,怎么做是应该的,很好,不是很明显,但至少可以理解的。

或者你也可以使用骨干关系,该做所有的工作适合你。

Is it possible to nest collections within models?

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'
      }
  ]
}

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.

解决方案

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.

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.

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

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

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