2011-11-23 9 views
6
window.User = Backbone.Model.extend({ 
    defaults: { 
    name: 'Jane', 
    friends: [] 
    },   

    urlRoot: "users", 

    initialize: function(){ 
    this.fetch(); 
    } 
}); 

    var HomeView = Backbone.View.extend({ 
    el: '#container', 
    template: _.template($("#home-template").html()), 

    render: function() { 
     $(this.el).html(this.template(this.model.toJSON())); 
     return this; 
    } 
    }); 

     home: function() { 
     var user = new User({id: 1}); 
     this.homeView = new HomeView({ 
      model: user 
     }); 
     this.homeView.render(); 
     }, 

Se están investigando los datos del modelo y los atributos de nivel raíz funcionan bien, pero el atributo que contiene una matriz de otros objetos no parece mostrarse.Backbone.js - Obtener matriz JSON en la plantilla de vista

Plantilla:

<script id="home-template" type="text/template"> 
     <div id="id"> 
     <div class="name"><%= name %></div> 
     <br /> 
     <h3> Single Friends</h3> 
     <br /> 
     <ul data-role="listview" data-inset="true", data-filter="true"> 
      <% _.each(friends, function(friend) { %> 
      <li> 
       <a href="/profile?id=<%= friend.id %>", data-ajax="false"> 
       <div class="picture"><img src="http://graph.facebook.com/<%= friend.fb_user_id %>/picture"></div> 
       <div class="name"><%= friend.name %></div> 
       </a> 
      </li> 
      <% }); %> 

     </ul> 
     </div> 
    </script> 

Volver JSON:

{"name":"John Smith","friends":[{"id":"1234","name":"Joe Thompson","fb_user_id":"4564"},{"id":"1235","name":"Jane Doe","fb_user_id":"4564"}]} 

Casi parece que no está viendo los .friends atribuyen en absoluto, porque está tomando los valores por defecto del modelo ([ ]).

¿Alguna sugerencia?

Respuesta

7

Está llamando render() antes de fetch() ha devuelto los datos del servidor.

¿Intenta esto?

window.User = Backbone.Model.extend({ 
    defaults: { 
    name: 'Jane', 
    friends: [] 
    }, 
    urlRoot: "users" 
}); 

var HomeView = Backbone.View.extend({ 
    el: '#container', 
    template: _.template($("#home-template").html()), 

    initialize: function() { 
    this.model.fetch(); 
    this.model.bind('change', this.render, this); 
    } 

    render: function() { 
    $(this.el).html(this.template(this.model.toJSON())); 
    return this; 
    } 
}); 
Cuestiones relacionadas