Backbone Live Collection End Point Fetch - Streaming

by f0t0n

HTML

<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone.js"></script>
<h1> Cat Tweets: </h1>
<div id="example_content"></div>

JavaScript

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

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

    render: function() {

        // just render the tweet text as the content of this element.
        $(this.el).html(this.model.id + ": " + this.model.get("text"));
        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 Tweets = StreamCollection.extend({
    model: Tweet,
    initialize: function(models, options) {
        this.query = options.query;
    },
    url: function() {
        return "http://search.twitter.com/search.json?q=" + this.query + "&callback=?";
    },
    parse: function(data) {

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

// A rendering of a collection of tweets.
var TweetsView =...