我有一个加载模型和一些模板的主 View 。当我在编辑模板中提交表单时, Backbone 便成功发送了一个PUT请求,正如预期的那样。成功后,我将用户导航回到 View 模板。
但是,如果我再次导航到编辑路径并提交表单,主干将发送两个PUT请求。然后,它获取 View 模板。如果我第三次导航到编辑路径,则主干发送三个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;
});
最佳答案
就我而言,我可以通过在成功回调中的 View 上调用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。