Reputation: 13332
I have a model that has a bunch of attributes but the two of interest here are id
and key
. key
is always unique, id
not so much. When I try to add more than one model with the same id
to a collection, I get this error:
Uncaught Error: Can't add the same model to a collection twice
I am guessing this is because backbone is using the id
to decide if two models are ===
. Is that correct? If so is there a way to override this behaviour without swapping the name of the id
and key
attributes? I tried messing around with the collection's comparator
but to no avail...
Upvotes: 3
Views: 3737
Reputation: 9
Backbone prevent us to insert the same model into one collection... You can see it in backbone.js line 676 to line 700
if you really want to insert the same models into collection,just remove the code there
if(existing = this.get(model)){//here
...
}
Upvotes: 0
Reputation: 5463
Yes, backbone uses and manages the id
attribute of a model for identification. If your data uses a different property, you can set the model's idAttribute
to the name of your property to make backbone read the id from this property:
var Entry = Backbone.Model.extend({
idAttribute: "key"
});
var entry = new Entry({ key: 1, name: "an entry" });
alert("entry id: " + entry.id);
However, you cannot use the model's id
property for anything else at the same time.
Upvotes: 8