Backbone.jsを使用して読み込んだJSONを表示するサンプル

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
<div id="list"></div>
<div id="listDetail"></div>
 
<script type="text/template" id="tempList">
<ul>
  <% _.each(model, v => { %>
    <li><%= v.name %> <%= v.age %></li>
  <% }) %>
</ul>
</script>
<script src="https://backbonejs.org/backbone.js"></script>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const Model = Backbone.Model.extend({})
const Collection = Backbone.Collection.extend({
})
const View = Backbone.View.extend({
  el: '#list',
  template: _.template($('#tempList').html()),
  collection: new Collection(),
  initialize() {
    this.collection.fetch()
    this.listenTo(this.collection, 'sync', this.render)
  },
  render() {
    const html = this.template({
      model: this.collection.toJSON()
    })
    this.$el.html(html)
  },
})
new View()

元記事を表示する