user2058320
user2058320

Reputation: 97

Backbone Collection Set method remove existing elements and then add all elements

I have a backbone collection.I want to add or remove some models dynamically in the collection. But if i am using collection.set() method then it is going to remove first all elements and then it will add all elements again.

What i want to do is trigger add event of collection for those whose are really new added and trigger remove events for those whose are removed from previous collection.

Here is a example [http://jsfiddle.net/PkJCx/2/]

Upvotes: 2

Views: 3104

Answers (1)

Sushanth --
Sushanth --

Reputation: 55740

From the docs

The set method performs a "smart" update of the collection with the passed list of models. If a model in the list isn't yet in the collection it will be added; if the model is already in the collection its attributes will be merged; and if the collection contains any models that aren't present in the list, they'll be removed.

It is also a good idea to provide `idAttribute' to the model so that the collection identifies that based on the id. Otherwise the collection would not know if the model is a new one or not.

So after setting the id and using set, you can see that is performs a smart update

$(function () {
    var MyModel = Backbone.Model.extend({ 
        // This attribute should be set as a default
        defaults: {
            Name: ''
        },
        // Set the id attribute so that the collection 
        // know that it is the old model
        idAttribute: 'id'

    });

    var Coll = Backbone.Collection.extend({
        model: MyModel
    });

    var models = [{
        Name: 'A',
        id: 1
    }, {
        Name: 'B',
        id: 2
    }];

    var collection = new Coll(models);

    collection.bind('add', function (model) {
        alert('addb')
    });
    collection.bind('remove', function () {
        alert('add')
    });


    models = [{
        Name: 'A',
        id :1
    }, {
        Name: 'B',
        id: 2
    }, {
        Name: 'C',
        id: 3
    }];
    collection.add(models);
});

Check Fiddle

It will not try to remove the other 2, but Backbone is smart enough to identify that 2 of them are old models and then just merges the newer one into the collection.

Upvotes: 1

Related Questions