[英]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.