2013-06-30 43 views
2

我一直在試圖通過調用 的REST API來呈現JSON數據的視圖和代碼如下:JSON數據骨幹視圖不會呈現

var Profile = Backbone.Model.extend({  
    dataType:'jsonp', 
    defaults: { 
     intuitId: null, 
     email: null, 
     type: null  
    }, 
});  
var ProfileList = Backbone.Collection.extend({  
    model: Profile,   
    url: '/v1/entities/6414256167329108895' 
});  
var ProfileView = Backbone.View.extend({   
    el: "#profiles", 
    template: _.template($('#profileTemplate').html()),   
    render: function() { 
     _.each(this.model.models, function(profile) { 
      var profileTemplate = this.template(this.model.toJSON()); 
      $(this.el).append(tprofileTemplate); 
     }, this); 
     return this;   
    } 
});  
var profiles = new ProfileList(); 
var profilesView = new ProfileView({model: profiles}); 
profiles.fetch(); 
profilesView.render(); 

和HTML文件如下:

<!DOCTYPE html> 
<html> 
    <head> 
     <title>SPA Example</title> 
     <!-- 
      <link rel="stylesheet" type="text/css" href="src/css/reset.css" /> 
      <link rel="stylesheet" type="text/css" href="src/css/harmony_compiled.css" /> 
     --> 
    </head> 
    <body class="harmony"> 
     <header>   
      <div class="title">SPA Example</div>  
     </header> 
     <div id="profiles"></div> 
     <script id="profileTemplate" type="text/template"> 
      <div class="profile"> 
       <div class="info"> 
        <div class="intuitId"> 
         <%= intuitId %> 
        </div> 
        <div class="email"> 
         <%= email %> 
        </div> 
        <div class="type"> 
         <%= type %> 
        </div> 
       </div> 
      </div> 
     </script> 
    </body> 
</html> 

這給了我一個錯誤,並且render功能不調用 正確和REST API 返回JSON響應甚至在render函數被調用。

任何人都可以請幫我弄清楚我出錯的地方。任何幫助都非常感謝 謝謝

回答

1

首先,您需要明確地將模型屬性傳遞給模板函數。因此,將視圖中的相應代碼更改爲:

var ProfileView = Backbone.View.extend({   
    el: "#profiles", 
    //template: _.template($('#profileTemplate').html()), REMOVED   
    render: function() { 
     _.each(this.model.models, function(profile) { 
      var profileTemplate = _.template($('#profileTemplate').html(), { 
        intuitId: profile.get("intuitId"), 
        email: profile.get("email"), 
        type: profile.get("type") 
       }); 
      $(this.el).append(tprofileTemplate); 
     }, this); 
     return this;   
    } 
}); 

其次,您的render方法不依賴於從服務器返回的獲取響應。它會在它執行的行之後立即被調用,而不是等待獲取響應。您遇到的這種行爲是通過設計。如果您想在從服務器獲取響應後調用渲染,則必須使用事件。你可能喜歡的東西取代profilesView.render();

profilesView.listenTo(profiles, "sync", profilesView.render); 

這意味着profilesView將監聽profiles收集完成其獲取和火sync事件。發生這種情況時,視圖的render函數將被調用。