我想知道是否有一个通用的模式来保存(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