TTT
TTT

Reputation: 1885

How to check if a backbone collection already contains a model with the same idAttribute?

My backbone model's idAttribute can be anything (Backbone's default is "id"). I would like to check before inserting the model in a Backbone collection if that collection already contains a model with the same idAttribute value.

myCollection.contains(myNewModel) is always returning false. I guess that's because the candidate model is not necessarily the same instance that is already in the collection.

I tried

idAttribute: string = myColllection.model.prototype.idAttribute; // Works fine
let id: string = itemToInsert.get(idAttribute); // Works fine
let exists : boolean : myCollection.findWhere({ idAttribute : id }); // Undefined!

I would like something like

let test: boolean = _.any(self.collection, item => idAttributeValue === item.get("idAttribute")).value();

but I'm not sure the precise syntax.

Upvotes: 0

Views: 666

Answers (1)

nikoshr
nikoshr

Reputation: 33344

You can use Collection.get to determine if a collection has a model with the given id, regardless of the underlying idAttribute.

For example,

var M = Backbone.Model.extend({
  idAttribute: 'whatever'
});
var C = Backbone.Collection.extend({
  model: M,
  hasModel: function(input) {
    return !!this.get(input);
  }
});

var c = new C([{whatever : 1}]);
console.log(c.hasModel(1)); // true
console.log(c.hasModel(2)); // false

var newModel = new M({whatever: 1});
console.log(c.hasModel(newModel)); // true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>

If you want to use findWhere, you would have to use the square bracket notation for your hash of attributes:

var finder = [];
var idAttribute = M.prototype.idAttribute;
finder[idAttribute] = 1;
console.log(c.findWhere(finder));

Upvotes: 1

Related Questions