2013-06-30 31 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函数将被调用。