SO - Fetching a collection

http://stackoverflow.com/q/8745183/1011582 http://stackoverflow.com/questions/8828919/backbone-js-collection-calling-fetch-repeatedly-to-get-all-pages-from-server

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.2/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js"></script>
<script src="https://raw.github.com/appendto/jquery-mockjax/master/jquery.mockjax.js"></script>
<div id="container">
    <button id="test">Run fetch</button> fetch() executed <span id="fetchnr">0</span> times!
    <ul id="students"></ul>
</div>

JavaScript

// mock of the /test so we can simulate server side
$.mockjax({
    url: '/test',
    contentType: 'text/json',
    responseText: [{"name": "Karen","grade": "C"},{"name": "Susan", "grade": "F"}]
});

var Student = Backbone.Model.extend({});

var Students = Backbone.Collection.extend({
    model: Student,
    url: '/test'
});

var AppView = Backbone.View.extend({

    el: '#container',
    events: {
        'click #test': 'fetchData'
    },

    initialize: function() {
        _.bindAll(this, 'render', 'fetchData');
        this.collection.bind('reset', this.render);
    },

    render: function() {
        var ul = $('#students').empty();

        this.collection.each(function(item) {
            $('<li>').text(item.get('name') + ': ' + item.get('grade')).appendTo(ul);
        });
    },

    fetchData: function() {
        var count = 0;
        var self = this;
        self.collection.fetch({ 
            success: function success() {
                // increment fetch counter.
                $('#fetchnr').text(+ $('#fetchnr').text() + 1);
                if (++count < 10) {
                    self.collection.fetch({ success: success });
                }
            }
        });
    }

});

var appview = new AppView({
    collection: new Students()
});