2012-11-28 27 views
5

我有以下代碼來創建集合的新模型。底層數據存儲在遠程API:Backbone model.create不能調用任何回調

 var postCreationStatus = this.model.create(newPostModel, { 
      wait : true  // waits for server to respond with 200 before adding newly created model to collection 
     }, { 
      success : function(resp){ 
       console.log('success callback'); 
       console.log(resp); 
      }, 
      error : function(err) { 
       console.log('error callback'); 
       console.log(err); 
      } 
     }); 

新模型被創建,我可以從數據庫中證實了這一點,但無論是成功還是錯誤回調被調用。

創建完成後,我想重定向用戶。過早重定向會殺死AJAX請求,這就是爲什麼它很重要我使用成功回調。

服務器響應一個JSON響應{ id : 11 }和一個HTTP狀態200 OK

+1

這個標題是不正確的,這個問題不是關於collection.create –

回答

6

縱觀骨幹代碼,我意識到我對create()函數的調用是錯誤的。成功和錯誤回調需要在作爲第二個參數傳入的對象內,而不是作爲第三個參數。改變和工作片段是這樣的:

var postCreationStatus = this.model.create(newPostModel, { 
    wait : true, // waits for server to respond with 200 before adding newly created model to collection 

    success : function(resp){ 
     console.log('success callback'); 
     console.log(resp); 
     that.redirectHomePage(); 
    }, 
    error : function(err) { 
     console.log('error callback'); 
     // this error message for dev only 
     alert('There was an error. See console for details'); 
     console.log(err); 
    } 
});