Backbone.js w/RESTful API

by Scott Currell

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/eu81273/jsfiddle-console/console.js"></script>
<ul id="js-spa-container"></ul>

JavaScript

var Post = Backbone.Model.extend();

var Posts = Backbone.Collection.extend({

  model: Post,

  url: 'https://jsonplaceholder.typicode.com/posts',
  
  fetchSuccess: function(collection, response) {
    console.log('Fetch response: ', response);
  },

  fetchError: function(collection, response) {
    throw new Error('fetch error');
  }
});

var PostView = Backbone.View.extend({

  tagName: 'li',

  render: function() {
    this.$el.html(this.model.get('title'));

    return this;
  }

});

var PostsView = Backbone.View.extend({

  render: function() {

    var _this = this;

    this.collection.each(function(post) {

      // Put the current post in the child view
      var _postView = new PostView({
        model: post
      });

      // Render the post and append it to the DOM element of the postsView.
      _this.$el.append(_postView.render().$el);
    });
  }

});

var posts = new Posts();

var postsView = new PostsView({
  el: '#js-spa-container',
  collection: posts
});

posts.fetch({
  success: postsView.render.bind(postsView),
  error: this.fetchError
});