Backbone.js:创建或更新花样,post保存花样

Backbone.js: create or update pattern, post save pattern

我想知道是否存在用于保存 (POST) 或更新 (PUT) 模型的通用模式,具体取决于该模型的实例是否已存在。我发现自己在我的代码中做了类似的事情

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);
            }
        }
    });
};

我从地方获取模型属性,创建一个新模型,获取模型,如果存在则使用设置的属性,如果它 returns 404,保存。这是可接受的设计模式吗?我是 backbone 的新手,想知道这是否是处理它的正确方法。

另外,在成功保存事件后,将用户发送到下一个 uri 的正确方法是什么?我知道你可以这样做: document.location.href = '/some/relative/url/' 并且它有效,但我来自 django 背景,在视图中处理重定向,我没有将 URL 硬编码到模板中。我不想再这样做了。

Backbone 检查模型是否定义了 id,当使用 RESTful 后端时,它自然应该对应于资源的后端 id。
如果模型上的id字段被设置,那么save会执行一个PUT请求,如果没有,它会生成一个POST请求。

通常,客户端在执行 PUT 请求之前知道 id,因为它意味着更新现有资源。
Backbone 并不真正关心你如何放置 id。您可以按照指示使用 GET 请求,也可以根据上下文从 DOM 获取 id。如果是当前登录用户的user id,也可以暂时存放在localstorage/cookie/global变量中,等用户退出时再移除。这样你就可以避免额外的 http 请求。

重定向最好立即通过锚点 href 完成,但如果必须先执行某些逻辑,我也会使用 location.href,因为这似乎是执行客户端重定向的最佳方式。