user911625
user911625

Reputation:

Backbone Marionette - trying to update one model in a collection deletes the other models

I have a Collection:

var initializeUpfrontCost = function () {
    Entities.upfrontCost = new Entities.UpfrontCostCollection([
        { id: 'upfrontcost', name: 'upfrontcost', value: 0},
        { id: 'upfrontcostquote', name: 'upfrontcostquote', value: 0}


    ]);
};

I want to update just one row (model). I have:

   Entities.upfrontCost.set({id: 'upfrontcostquote', value:  "somevalue"});

But this seems to delete the other row. (A remove event is fired).

How can I update just this one row in my Collection?

Thanks

--Justin Wyllie

Upvotes: 0

Views: 1289

Answers (2)

Isaac Suttell
Isaac Suttell

Reputation: 469

Check out the documentation on collection.get(id)

You should be able to do something like:

var entity = Entities.upfrontCost.get('upfrontcostquote');

//Returns a model which you can then modify
entity.set({
   value: "some value"
});

When you call collection.set() in your original code it sets the value of the collection to the new input you gave it. Instead what you want to do is pull the individual Model out of the collection and modify that instead.

Upvotes: 1

Balint Bako
Balint Bako

Reputation: 2560

You need add({row}, {index: n}) to insert a row in the collection (or add({row}) if you don't care about the position of the new row), but you must know which row to remove, so you can call remove({oldrow}).

You can find out the index for the add call with _.indexOf(collection, {row});

If the add&row is not good enough, then you have to update the object in the collection and not replace it.

Links:

http://underscorejs.org/#indexOf

http://backbonejs.org/#Collection-add

Upvotes: 1

Related Questions