Backbone Live Collection End Point Fetch - Streaming

by iros

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script>
<h1> Repos: </h1>
<div id="example_content"></div>

JavaScript

// A container for a repo object.
var Repo = Backbone.Model.extend({});

// A basic view rendering a single repo
var RepoView = Backbone.View.extend({
    tagName: "li",
    className: "repo",

    render: function() {

        // just render the repo name and description as the content of this element.
        $(this.el).html(
            '<b>' + this.model.get("name") + "</b> - " +    
            this.model.get("description"));
        
        return this;
    }
});

// Create a StreamCollection
var StreamCollection = Backbone.Collection.extend({
    stream: function(options) {
        
        // Cancel any potential previous stream
        this.unstream();
        
        var _update = _.bind(function() {
            this.fetch(options);
            this._intervalFetch = window.setTimeout(_update, options.interval || 1000);
        }, this);

        _update();
    },

    unstream: function() {
        window.clearTimeout(this._intervalFetch);
        delete this._intervalFetch;
    },
    
    isStreaming : function() {
         return !_.isUndefined(this._intervalFetch);   
    }
});

// A collection holding many tweet objects.
// also responsible for performing the
// search that fetches them.
var Repos = StreamCollection.extend({
    model: Repo,
    initialize: function(models, options) {
        this.language = options.language;
    },
    url: function() {
        return "https://api.github.com/search/repositories?q=language:" + 
               this.language + "&sort=stars&order=desc";
    },
    parse: function(data) {

        // note that the original result contains repos inside of an items array, not at 
        // the root of the response.
        return data.items;
    },
    add: function(models, options) {
        var newModels = [];
        _.each(models, function(model) {
            if (typeof this.get(model.id) === "undefined") {
                newModels.push(model);
            }
        }, this);
        return...