jahilldev
jahilldev

Reputation: 3812

Backbone.js - Replace existing model in collection

I have the following collection:

UsersMod.users_list = Backbone.Collection.extend({

    add : function(model) {

        var duplicate = this.any(function(_model) { 

            return _model.get('user') === model.get('user');

        });

        if (duplicate) {

            return false;

        }

        Backbone.Collection.prototype.add.call(this, model);

    }

});

This currently checks for a duplicate model in the collection and returns false if one is found. What I'm trying to do is when a duplicate is found, remove the old one and replace it with the new one.

Any help is much appreciated, thanks in advance :)

Upvotes: 3

Views: 4302

Answers (1)

Erik Hinton
Erik Hinton

Reputation: 1946

Try this:

UsersMod.users_list = Backbone.Collection.extend({

    add : function(model) {

        var duplicates = this.filter(function(_model) { 

            return _model.get('user') === model.get('user');

        });

        if (! _(duplicates).isEmpty) {

            this.remove(duplicates);

        } 

        Backbone.Collection.prototype.add.call(this, model);

    }

});

Upvotes: 2

Related Questions