Search code examples
javascriptjquerybackbone.js

Backbone: Fetch models in increments


Currently I am fetching a collection that has over 1000 models which has a decent delay. How can I fetch 50 at a time? Also, is it possible to hit a "more" button to fetch another 50 that is not currently there?

Trying to advoid grabing the entire collection at once and have more of a "lazy loading" type of scheme.

Here is my current render method

render: function(){
        var self = this
        var collection = this.collection

        collection.each(function(tenant){ 
            var view = new TenantView({
                model: tenant, 
                collection: collection 
            })
            self.$el.append(view.render().el) 
        })
        return this
    }

Solution

  • You have to specify {add: true} and your pagination arguments in collection.fetch call. It will append to collection instead of reseting its contents.

    collection.fetch({data: {page: 3}, add: true})
    

    Then simply listen to collection's add event and append item to your view.

    UPDATE: in the current version of backbone you need to call:

    collection.fetch({data: {page: 3}, remove: false});