admin管理员组

文章数量:1331640

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 parator but to no avail...

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 parator but to no avail...

Share Improve this question edited May 6, 2013 at 17:48 Chris Pfohl 19.1k9 gold badges72 silver badges115 bronze badges asked Feb 8, 2012 at 22:48 MatthewMatthew 13.3k6 gold badges43 silver badges45 bronze badges 2
  • Possible duplicate: stackoverflow./questions/6724025/… – Alex Morales Commented Feb 8, 2012 at 23:13
  • stackoverflow./questions/6724025/… – Alex Opak Commented Sep 28, 2012 at 12:08
Add a ment  | 

2 Answers 2

Reset to default 8

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.

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
      ...
}

本文标签: javascriptCannot add a model to backbone collectionStack Overflow