Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Models in more than one collection?

I'm kinda lost so any help would be much appreciated. (I’m using Backbone.js and CoffeeScript.)

I have a group of models. They are all put in MasterCollection.

MasterCollection extends Backbone.Collection
    model: Model

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

I need to separate these models at times and process their attributes in batches. These batches also need to have a corresponding DOM view that can show all of the models’ data.

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
  • When this model is changed by the batch, will it update the model in the MasterCollection?
  • When I’m done with a batch collection, how do I get rid of it without deleting its models?
  • Should I store these batch collections in something better than an array? Should they be models?

Since I need the DOM to bind to the creation of new batches, having them as models in a collection would be great.

Is this a good way to do this type of thing overall?

Thanks!

like image 613
fancy Avatar asked Dec 21 '25 07:12

fancy


1 Answers

When this model is changed by the batch it will update the model in the MasterCollection?

Since you're doing

batch.add(@toJSON)

you're really just adding a clone of the model to the batch collection. So, when you change that collection's model's attributes, the originals won't be affected.

Of course, these are shallow copies, so if you do something like

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

you will be modifying the attr attribute of the original. (You also won't trigger any change events.) This is a no-no with Backbone in general. Instead, do something like

attrCopy = _.extend {}, batch.at(0).get 'attr'
attrCopy.x = y
batch.at(0).set attr: attrCopy
like image 73
Trevor Burnham Avatar answered Dec 22 '25 20:12

Trevor Burnham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!