2011-10-21 74 views
2

我希望我能抽象出所有相關的部分。我的問題是爲什麼當我從服務器獲取我的模型時,render方法沒有執行。骨幹模型提取刷新事件不能觸發

型號

var Document = Backbone.Model.extend({ 
    urlRoot: "/dms/reconcile/GetDocumentByDocumentId/" 
}); 

查看

window.DocumentView = Backbone.View.extend({ 
    el: $("#reconcile_document"), 
    initialize: function() { 
     this.model.bind('refresh', this.render) //also tried reset 
    }, 
    render: function() { 

     alert("Do awesome stuff here"); 

     return this; 
    } 
}); 

路線

 var AppRouter = Backbone.Router.extend({ 
      routes: { 
       "package/:id": "getPackage" 
      }, 
      getPackage: function (packageid, p) { 

       window._document = new Document({ id:packageid) }); 
       window.document = new DocumentView({ model: _document }); 

       _document.fetch(); 
      } 
     }); 

     // Instantiate the router 
     var app_router = new AppRouter; 

所以,當我去localhost:3000/#/Package/123我可以看到xhr調用localhost:3000/dms/reconcile/GetDocumentByDocumentId/123,數據成功返回,但render函數從不執行。任何幫助將不勝感激。

乾杯。

回答

8

在模型上調用fetch()不會觸發refresh事件。它獲取數據後,它會通過調用setchange事件:

http://documentcloud.github.com/backbone/docs/backbone.html#section-40

http://documentcloud.github.com/backbone/#Model-fetch

更改您的事件處理程序,它應該工作:

window.DocumentView = Backbone.View.extend({ 
    el: $("#reconcile_document"), 
    initialize: function() { 
     this.model.bind('change', this.render, this); 
    }, 
    render: function() { 

     alert("Do awesome stuff here"); 

     return this; 
    } 
}); 
+3

或者,你可以調用_document.fetch({success:_document.success_handler})。在success_handler中,您可以觸發模型上的自定義事件。 – dira

+0

我很欣賞它Derick,我完全忽略了在文檔中。但事實證明,我還需要在文檔模型中的解析方法中設置對模型的響應。謝謝你的幫助。 –