多个系列中的型号?

时间:2011-11-07 19:11:46

标签: javascript backbone.js coffeescript

我有点失落所以任何帮助都会非常感激。 (我正在使用Backbone.js和CoffeeScript。)

我有一组模特。它们全部放在MasterCollection

MasterCollection extends Backbone.Collection
    model: Model

MasterCollection.add({#attributes of a new model})

我有时需要将这些模型分开并分批处理它们的属性。这些批次还需要有一个相应的DOM视图,可以显示所有模型的数据。

Model extends Backbone.Model
    initialize: () ->
        #add the model to it's batch, batches are collections stored in an array
        batches = ParentModel.get('baches')

        #find the batch this model belongs in
        for batch in batches
            if batch = #the right one
                batch.add(@toJSON)

Batch extends Backbone.Collection
    changeAttributes: () ->
        for model in @models
            #change things about the model
  • 批量更改此模型时,是否会更新MasterCollection
  • 中的模型
  • 当我完成批量收集时,如何在不删除其模型的情况下摆脱它?
  • 我应该将这些批量集合存储在比数组更好的东西中吗?它们应该是模特吗?

由于我需要将DOM绑定到新批次的创建,因此将它们作为集合中的模型将会很棒。

这是整体做这类事情的好方法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

  

当批次更改此模型时,它将更新MasterCollection中的模型吗?

因为你正在做

batch.add(@toJSON)

你真的只是将模型的克隆添加到batch集合中。因此,当您更改该集合的模型属性时,原件不会受到影响。

当然,这些是浅色副本,所以如果你做的话

(batch.at(0).get 'attr').x = y

修改原始版本的attr属性。 (您也不会触发任何更改事件。)这是一般的Backbone禁止。相反,做一些像

这样的事情
attrCopy = _.extend {}, batch.at(0).get 'attr'
attrCopy.x = y
batch.at(0).set attr: attrCopy
相关问题