[英]how can I update a model with custom idAttribute
在我简单的主干应用程序中,我试图更新模型,并在每次发送放置请求而不是发布时进行更新。
好吧,这是我的模型,名为categoryModel
define(['Backbone'], function (Backbone) {
var CategoryModel = Backbone.Model.extend({
defaults: {
ID: '',
Name: 'Empty',
TagID: '0',
GID: '0'
},
idAttribute: "ID",
initialize: function () {
if (!this.get('Name')) {
this.set({ 'Name': this.defaults.Name });
}
}
});
return CategoryModel;
});
这是集合
define(['Backbone','../../models/categories/categoryModel'], function (Backbone, categoryModel) {
var CategoryCollection = Backbone.Collection.extend({
url: '/parentcategory/Actions',
model: categoryModel
});
return new CategoryCollection;
});
这是我认为的方法
在关键keychange event
createNewItem: function (e) {
var $this = $(e.currentTarget);
$('#selectedCategoryName').html($this.val());
//it creates a new model
globals.NewCategory = new CategoryModel({ Name: $this.val() });
}
在handleDrop event
handleDropEvent: function (event, ui) {
var draggable = ui.draggable;
//check if name has set
if (!globals.NewCategory) {
alert("Please write a category name");
$('#createNewCategory').focus();
return;
}
//get itemID
var itemID = draggable.attr("id").split('_')[1];
var itemDesc = draggable.attr("id").split('_')[0];
//check items category
if (itemDesc == "Tag") {
//check if tagID already exists
if (globals.NewCategory.TagID) {
alert("you have already specify a tag from this category");
return;
}
globals.NewCategory.set("TagID", itemID);
} else if (itemDesc == "gTag") {
if (globals.NewCategory.GID) {
alert("you have already specify a tag from this category");
return;
}
globals.NewCategory.set("GID", itemID);
}
categoriesCollection.create(globals.NewCategory, {
silent: true,
wait: true,
success: function (model, response) {
model.set("ID", response);
alert(model.id);
}
});
}
categoryCollection.create被调用两次。 首先,用于设置TagID(在成功请求时,它获得ID),其次用于设置GID。 既然已经设置了ID,那么在第二个调用中不应该发送POST请求而不是PUT吗?
我究竟做错了什么?
谢谢
该标准的行为是发送POST
如果模型是新的(没有一个ID归因),并发送一个PUT
如果模型ID设置。
在您的情况下,它按设计工作,如果您希望它使用POST
发送更新,则必须重写Backbone.sync才能按需工作,但是我认为使后端RESTful并创建PUT
侦听器控制器方法更容易。进行更新。
另一件事,如果我做对了,您正在使用create()
来更新集合中的模型,我建议您不要这样做,而直接在要更新的模型中使用save()
,代码将是更具可读性。
干杯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.