[英]Backbone.js: Collection containing multiple Models with same ID
I've a merged collection in Backbone which contains photos and albums. 我在Backbone中有一个合并的集合,其中包含照片和相册。
To distinguish between them, i've added a field type
which is either photo
or album
. 为了区分它们,我添加了一个字段
type
,即photo
或album
。 When I populate the collection, I create different models within the Collection#model
method 当我填充集合时,我在
Collection#model
方法中创建了不同的模型
model: (attrs, options) ->
switch attrs.type
when 'album' then new App.Models.Album(attrs, options)
when 'photo' then new App.Models.Photo(attrs, options)
Now I've discoverd a strange bug where adding a photo and an album with the same ID (let's say 2
) results in a merge. 现在我发现了一个奇怪的错误,即添加照片和具有相同ID的相册(假设为
2
)会导致合并。
I've tracked this down to these LOC in the source code. 我在源代码中跟踪了这些 LOC。 It seems that it's undoable without creating a fork of Backbone itself.
似乎它没有创建一个Backbone本身的分支是可以撤销的。 I've tried it but it also fails 35 tests .
我已经尝试过,但它也没有通过35次测试 。
I thought of 4 different ways of doing this, I don't know which of them is the better one: 我想到了4种不同的方法,我不知道哪一种更好:
photo_2
. photo_2
。 This causes a change in the backend as well as some changes in the frontend to don't hit the server at /photos/photo_2
/photos/photo_2
命中服务器 1000000
. 1000000
。 This would extremely decrease the probability that a given user which has uploaded a photo with a given ID has also created an album with the same ID. I would suggest that on both Album and Photo, you add the following: 我建议在相册和照片上添加以下内容:
idAttribute: 'uniqueId'
parse: function(response) {
response.uniqueId = type+'_'+response.id
return response;
}
Since version 1.2 you can use Collection.modelId
to specify how your collection will uniquely identify models. 从版本1.2开始,您可以使用
Collection.modelId
指定集合如何唯一地标识模型。 In your case, you can do the following to ensure that your types have different IDs. 在您的情况下,您可以执行以下操作以确保您的类型具有不同的ID。
var MyCollection = Backbone.Collection.extend({
modelId: function (attrs) {
return attrs.type + "-" + attrs.id;
}
// ...
})
idAttribute:'uniqueId'
if this uniqueId is not known while declaring, try 如果在声明时不知道这个uniqueId,请尝试
idAttribute:'UUID'
I generated one from https://www.uuidgenerator.net/ and put it here, this attribute defined here need not be in model, so I just put in a UUID. 我从https://www.uuidgenerator.net/生成一个并把它放在这里,这里定义的这个属性不需要在模型中,所以我只是放入一个UUID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.