Search code examples
backbone.js

BackboneJS How to load more models in collection by using click event


How can I load more models into my Collection by using Backbone's click event method?

I have the following Collection:

MyCollection = Backbone.Collection.extend({
    parse: function(response){
        return response.data.posts.slice(0,10);
    },
});

this gives me 10 models. So far so good, now I want to load additional 10 models into the collection each time I click a button. How can I achieve this?

inside my view I have added this:

events: {
    'click .more': 'showMore'
},
showMore: function(){
   // show more functionality  
},

What to do next? Please help...


Solution

  • After chat discussion goal is to get first 10 post from API JSON on button click. As response is dynamic we cant parse collection once and then slice it on every click, so one of solution use flag on collection instance to control collection array slice:

    MyCollection = Backbone.Collection.extend({
        step: 0,
        parse: function(response){
            var slice = response.data.posts.slice(this.step*10,(this.step+1)*10)
            this.step++;
            return slice;
        }
    });