Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackboneJS: Load more items into a collection

In Backbone JS when I fetch a collection should I be fetching the entire collection or a small portion of it?

For example I have news feed collection in mongoDB that could have potentially 1000s of items. When the user hits the page I only want to show them the latest 10 items with the option to 'Load More'. But if they visit a specific item via URL http://site.com/#/feed/:itemID I want to be able to pull up that item's record.

1. How many document should I be fetching initially?

2. How would I got about fetching any item by id?

like image 967
wilsonpage Avatar asked Oct 13 '11 17:10

wilsonpage


Video Answer


1 Answers

I ended up using the {add: true} statement when calling fetch on my collection. This prevents the collection from being replaced by the result of the fetch and but instead appends the result to the collection. I then also passed the 'skip' amount using the {data: {skip: amountOfItemsInCollectionAlready }, this is used on the server-side to get the correct batch of items from the database.

My final fetch method looks like this:

    loadMore: function(e){

        this.collection.fetch({
            add: true,// this adds to collection instead of replacing
            data:{// this is optional params to be sent with request
                skip: this.collection.length// skip the number of items already in the collection
            }
        });
    }
like image 85
wilsonpage Avatar answered Sep 28 '22 13:09

wilsonpage