我想知道是否有一個通用的模式來保存(POST)或更新(PUT)模型取決於該模型的實例是否已經存在。我發現自己做這樣的事情在我的代碼Backbone.js:創建或更新模式,發佈保存模式
var UserProfileModel = Backbone.Model.extend({
urlRoot: '/api/v1/userprofile'
});
function upsave(){
var userprofile = new UserProfileModel({
user: self.user_id,
user_type: self.user_type,
userprofile_complete: true
});
userprofile.fetch({
success: function(model, response, options) {
//model exists and is now populated
userprofile.set('user_type', self.user_type);
userprofile.set('userprofile_complete', true);
userprofile.save();
},
error: function(model, xhr, options) {
if(xhr.status === 404) {
//model was not found
userprofile.save();
}
else {
alert('The server encountered an error saving the user profiile');
console.log(xhr.status);
}
}
});
};
我從地方的模型屬性,創建一個新的模型,取模型,如果存在使用設置屬性,如果返回404,保存。這是一個可接受的設計模式?我是新手,想知道這是否是正確的處理方法。
而且,在成功保存事件後,將用戶發送到下一個uri的正確方法是什麼?我知道你可以這樣做:document.location.href = '/some/relative/url/'
,這是有效的,但我來自django背景,在視圖中處理重定向,我不是將URL硬編碼到模板中。我想不回去這樣做。
Backbone(同步)會自動爲您執行此操作,具體取決於模型是否已具有「id」屬性,因此在服務器上是否存在。所以,只需調用'model.save()' - 它會發佈一個新模型並放入一個現有模型。保存時不要原封不動地從服務器返回整個模型。 – Exinferis 2015-03-02 14:41:59
這就是我最初的想法,但沒有第一次獲取save()函數會自動生成一個沒有'id'的POST。服務器端的原因和錯誤500。 – ghiotion 2015-03-02 14:54:39