2013-07-08 149 views
3

我有一個加載模型和一些模板的骨幹視圖。當我在編輯模板中提交表單時,骨幹成功地發送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; 

}); 
+4

快速思考,你分配/創建一個新的後,你取消了UserEdit視圖?請參閱Derick Bailey的[post](http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/) – dbf

+0

因爲我不確定,我要說「不」:) –

+0

繼續在@dbf去,我會在createUser函數中添加console.log,看看它是否被調用兩次 – ekeren

回答

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。

+0

在我的情況下,儘管在骨幹'save'的成功回調中添加了'that.undelegateEvents()',骨幹仍多次發送post請求。任何想法,爲什麼會發生? – Raeesaa

+0

@ user2235057你把那個'綁定到了什麼? –

+0

我已將它綁定到當前的骨幹視圖。 – Raeesaa