Question

var collection = new Backbone.Collection([
  {key:1,name: "Tim", age: 5},
  {key:2,name: "Ida", age: 26},
  {key:3,name: "Rob", age: 55}
]);

i am going to add the model

{key:4,name: "Rob", age: 55}

Here since the key is different, backbone will not give an error. How do I check for an existing model in the collection before adding?

Was it helpful?

Solution

A Backbone model has a concept of an idAttribute (http://backbonejs.org/#Model-idAttribute) that is used for duplicate checking when adding to a collection.

This may not work for you because it seems your idAttribute would be 'key' which is continuously incrementing.

Instead you could check in code via:

var newModel = {key:4,name: "Rob", age: 55};

var similarModel = collection.findWhere({name: newModel.name, age: newModel.age});

if(!similarModel) {
   //add to collection
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top