JSFiddle - React, Tailwind, and code Playground

by davidsulc

HTML

<script src="https://raw.github.com/documentcloud/underscore/master/underscore.js"></script>
<script src="https://raw.github.com/documentcloud/backbone/master/backbone.js"></script>

JavaScript

var Book = Backbone.Model.extend({
  parse: function(results) {
    if (!results.volumeInfo)
        return {};

    return _.extend(results.volumeInfo, {
      id: results.id
    });
  }
});

var Books = Backbone.Collection.extend({
  model: Book,
  urlRoot: 'https://www.googleapis.com/books/v1/volumes',
  
  initialize: function(models, options){
    // search query
    this.searchTerm = options.searchTerm || '';     
    // the number of books we fetch each time
    this.maxResults = options.maxResults || 40;

    // the results "page" we last fetched
    this.page = options.page || 0;
    // flags whether the collection is currently in the process of fetching
    // more results from the API (to avoid multiple simultaneous calls
    this.loading = false;
    
    // the maximum number of results for the previous search
    this.totalItems = null;
  },
  url: function(){
    var query = encodeURIComponent(this.searchTerm)+'&maxResults='+this.maxResults+'&startIndex='+(this.page * this.maxResults)+'&fields=totalItems,items(id,volumeInfo/title,volumeInfo/subtitle,volumeInfo/authors,volumeInfo/publishedDate,volumeInfo/description,volumeInfo/imageLinks)';
    return this.urlRoot + '?q=' + query;      
  },
  parse: function(results){
    this.loading = false;
    // MyApp.vent.trigger("search:stop");
    this.page++;
    this.totalItems = results.totalItems;

    return results.items;
  },
  fetch: function(options){
    if (this.loading) return;

    this.loading = true;
    // MyApp.vent.trigger("search:start");

    return Backbone.Collection.prototype.fetch.apply(this, arguments);
  }
});

var bookSearch = new Books([], {
  searchTerm: 'Neuromarketing'
});

// Load page 1.
bookSearch.fetch({
  success: function() {
    console.log('should be false:', bookSearch.loading);
    console.log('should be 1:', bookSearch.page);
    console.log('should be 40:', bookSearch.size());

    // Now load and add page 2 to collection.
    bookSearch.fetch({
      add: true,
  ...