0

我试图将我的 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
    }

]

请帮助我....我不知道哪里有问题或缺少什么。

4

1 回答 1

1

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

于 2013-08-12T13:07:56.243 回答