是否可以为 Backbone collection 中的新模型生成唯一 ID?
Is it possible to generate a unique id for new models in Backbone collection?
我有一个来自 serer 的 Backbone collection 属性 id
和 name
.
我从输入中得到新名字。
var a = $('#newFoodtype').val();
并创建新模型并添加到 collection;
var b = new app.Foodtype({ "name" :a });
this.collection.add(b);
新模型没有 id
属性。我知道所有模型都有 id
。
如何生成唯一 ID 并将其设置为新模型。
我会删除collection中的一些模型,因此collection.length
是个好主意。我会将其发送到服务器。一种解决方案是在插入数据库期间仅发送 "name"
并在服务器上生成 "id"
。
是否可以从客户端生成这个?
One solution is to send only the "name"
and generate the "id"
on the server during the insert to the DB.
id
,如果保存在数据库中,应该由数据库处理。永远不要尝试增加最后一个id或使用集合长度作为唯一标识符。
临时客户 ID:cid
Backbone 给模型和视图一个 cid
property,这是一个 "client id"。它仅对该客户端实例是唯一的,刷新后将不再是唯一的。它用于在保存模型并为其提供最终 ID 之前识别模型。
var newModel = Backbone.Model({ name: "new model" });
console.log(newModel.cid); // e.g.: "c123"
正在生成 GUID
如果它不是数据库的 id,而只是业务逻辑的唯一标识符,您可以生成一个冲突几率较低的 GUID。
见Create GUID / UUID in JavaScript?
我有一个来自 serer 的 Backbone collection 属性 id
和 name
.
我从输入中得到新名字。
var a = $('#newFoodtype').val();
并创建新模型并添加到 collection;
var b = new app.Foodtype({ "name" :a });
this.collection.add(b);
新模型没有 id
属性。我知道所有模型都有 id
。
如何生成唯一 ID 并将其设置为新模型。
我会删除collection中的一些模型,因此collection.length
是个好主意。我会将其发送到服务器。一种解决方案是在插入数据库期间仅发送 "name"
并在服务器上生成 "id"
。
是否可以从客户端生成这个?
One solution is to send only the
"name"
and generate the"id"
on the server during the insert to the DB.
id
,如果保存在数据库中,应该由数据库处理。永远不要尝试增加最后一个id或使用集合长度作为唯一标识符。
临时客户 ID:cid
Backbone 给模型和视图一个 cid
property,这是一个 "client id"。它仅对该客户端实例是唯一的,刷新后将不再是唯一的。它用于在保存模型并为其提供最终 ID 之前识别模型。
var newModel = Backbone.Model({ name: "new model" });
console.log(newModel.cid); // e.g.: "c123"
正在生成 GUID
如果它不是数据库的 id,而只是业务逻辑的唯一标识符,您可以生成一个冲突几率较低的 GUID。
见Create GUID / UUID in JavaScript?