admin管理员组文章数量:1331888
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...
- 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
2 Answers
Reset to default 8Yes, 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
版权声明:本文标题:javascript - Cannot add a model to backbone collection - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742270934a2444291.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论