Backbone.js model.save()发送多个PUT请求

时间:2013-07-08 11:54:41

标签: javascript jquery model-view-controller backbone.js

我有一个骨干视图,可以加载模型和一些模板。当我在编辑模板中提交表单时,骨干成功地发送了一个PUT请求,就像它应该的那样。成功后,我将用户导航回视图模板。

但是,如果我再次导航到编辑路径并提交表单,则骨干网会发送两个 PUT请求。然后它获取视图模板。如果我第三次导航到编辑路径,则骨干网发送三个 PUT请求。每次提交表单时,PUT请求的数量都会递增。为什么会这样?

以下是我的观点:

// Filename views/users/edit.js
/*global define:false */

define([
    'jquery',
    'underscore',
    'backbone',
    'models/user/UserModel',
    'text!templates/users/edit.html',
], function($, _, Backbone, UserModel, UserTemplate) {

    var UserEdit = Backbone.View.extend({
        el: '#page',
        render: function (options) {

            var that = this;

            if (options.id) {
                // modify existing user
                var user = new UserModel({id: options.id});
                user.fetch({
                    success: function (user) {
                        var template = _.template(UserTemplate, {user: user});
                        that.$el.animate({opacity: 0}, 180, function() {
                            that.$el.html(template).animate({opacity: 1}, 180);
                        });
                    }
                });
            } else {
                // create new user
                var template = _.template(UserTemplate, {user: null});
                that.$el.animate({opacity: 0}, 180, function() {
                    that.$el.html(template).animate({opacity: 1}, 180);
                });
            }

        },
        events: {
            'submit #create-user-form': 'createUser'
        },
        createUser: function (e) {
            var postData = $(e.currentTarget).serializeObject();
            var user = new UserModel();
            user.save(postData, {
            success: function (user, response) {
                Backbone.history.navigate('#/users/view/' + response, {trigger: true, replace: true});
                }
            });
            return false;
        }
    });

    return UserEdit;

});

1 个答案:

答案 0 :(得分:6)

就我而言,我可以通过在成功回调中的视图上调用undelegateEvents()来修复它。

createUser: function (e) {
    var postData = $(e.currentTarget).serializeObject(),
            user = new UserModel(),
            that = this;

    user.save(postData, {
        success: function (user, response) {
            that.undelegateEvents();
            Backbone.history.navigate('#/users/view/' + response, {trigger: true});
        }
    });

    return false;
}

谢谢,@ dbf。