Backbone Collection Fetch Scheduler

A simple method to orchestrate the fetching of several collections used in a Backbone application.

by Adam Boduch

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.5.3/jquery.mockjax.js"></script>

CSS

body {
    font: 0.8em "Lucida Console", Monaco, monospace
}

p {
    margin: 2px 0 0 0;
}

JavaScript

(function( $ ) {
    
    // Utility logger for fetch messages.
    function log( msg ) {
        $( "<p/>" ).text( msg ).appendTo( "body" );
        window.scrollTo( 0, document.body.scrollHeight );
    }
    
    // Mock API data...
    var usersJSON = [
        { id: 1, name: "User 1" },
        { id: 2, name: "User 2" },
        { id: 3, name: "User 3" }
    ];
    
    var pagesJSON = [
        { id: 1, name: "Page 1" },
        { id: 2, name: "Page 2" },
        { id: 3, name: "Page 3" }
    ];
    
    var commentsJSON = [
        { id: 1, name: "Comment 1" },
        { id: 2, name: "Comment 2" },
        { id: 3, name: "Comment 3" }
    ];

    // Mock API endpoints...
    $.mockjax({
        url: "/api/users",
        responseTime: 100,
        dataType: "json",
        response: function( options ) {
            this.responseText = usersJSON
        }
    });
    
    $.mockjax({
        url: "/api/pages",
        responseTime: 6000,
        dataType: "json",
        response: function( options ) {
            this.responseText = usersJSON
        }
    }); 

    $.mockjax({
        url: "/api/comments",
        responseTime: 10000,
        dataType: "json",
        response: function( options ) {
            this.responseText = usersJSON
        }
    });
    
    // The Backbone collections
    var Users = Backbone.Collection.extend({
        url: "/api/users"    
    });
    
    var Pages = Backbone.Collection.extend({
        url: "/api/pages"    
    });

    var Comments = Backbone.Collection.extend({
        url: "/api/comments"
    });
    
    // The fetcher. It tries to orchestrate the fetching of all
    // collections in the application while keeping contention
    // to a minimum
    var Fetcher = function( collections ) {
        
        // The wait time between each fetch.
        this.wait = 3000;
        
        // The maximum number of outstanding Ajax requests.
        this.concurrency = 2;
        
        // Sets the collections...