我有一個加載模型和一些模板的骨幹視圖。當我在編輯模板中提交表單時,骨幹成功地發送PUT請求,就像它應該的那樣。成功後,我將用戶導航回視圖模板。Backbone.js model.save()發送多個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;
});
快速思考,你分配/創建一個新的後,你取消了UserEdit視圖?請參閱Derick Bailey的[post](http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/) – dbf
因爲我不確定,我要說「不」:) –
繼續在@dbf去,我會在createUser函數中添加console.log,看看它是否被調用兩次 – ekeren