渲染所有json对象?

时间:2013-08-12 09:10:43

标签: json backbone.js

我试图将我的json文件/api/tables.json中的所有对象名称都渲染成? <li>there</li>

var Table = Backbone.Model.extend({
defaults: {
    name: 'table',
    id: 1
}
});

var Tables = Backbone.Collection.extend({
model: Table,
url: 'api/table.json'
});

var TablesView = Backbone.View.extend({

el: '#mydiv',

template: _.template($("#table-template").html()),

initialize : function() {
  this.coll = new Tables()
  this.listenTo(this.coll, 'reset', this.render);
  this.coll.fetch();              
},
render : function() {
  this.$el.html(this.template({ table: this.coll.toJSON() }));
  return this;
}

});

这是我在index.html中的模板:

    <div id="mydiv"></div>
    <script type="text/template" id="table-template">
      <ul> 
        <% _.each(table, function(table)  { %>
          <li><%= table.name %></li>
        <% }); %>
      </ul>
    </script>

来自json文件的数据:

[
    {
        "name": "Table 1",
        "id": 1
    },

    {
        "name": "Table 2",
        "id": 2
    },

    {
        "name": "Table 3",
        "id": 3
    },

    {
        "name": "Table 4",
        "id": 4
    }

]

请帮助我......我不知道哪里出错或者遗漏了什么。

1 个答案:

答案 0 :(得分:1)

我强烈建议使用Backbone.Marionette插件,该插件支持立即呈现列表。您不必为它编写样板代码。只需将CollectionViewCompositeView与作为构造函数参数给出的集合一起使用,并为它们定义ItemView(li元素)

相关问题