Backbone.js - 将JSON数组放入视图模板

时间:2011-11-23 14:31:18

标签: javascript json backbone.js

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();
      },

正在查询模型数据,并且根级别属性正常工作,但包含其他对象数组的属性似乎不会显示。

模板:

   <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>

返回JSON:

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

它几乎看起来根本没有看到.friends属性,因为它采用了模型的默认值([])。

有什么建议吗?

1 个答案:

答案 0 :(得分:7)

render()从服务器返回数据之前,您正在调用fetch()

试试这个?

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;
  }
});