Mr_Green
Mr_Green

Reputation: 41842

Get same Item collection but with different limits

In my Backbone project, I am getting a collection of Items through the following Model:

MyApp.models.Items = Backbone.Model.extend({
    url: "getItems"
});

and then later:

var model = new MyApp.models.Items();
model.fetch().then(function(data){
    // do something here with fetched data
});

This Implementation works fine but I have a situation where I am getting all the Items on Home page and only 3 items in other page.

I feel it will be overkill if I fetch all the Items and then using the above model to limit it to 3 Items.

How can I use the same model to get a limited number of items or all items?

PS: I am new to Backbone.

Upvotes: 0

Views: 69

Answers (2)

Chen-Tai
Chen-Tai

Reputation: 3473

In your scenario, you say you fetch all the items in homepage and only use part of it in other page.

For me, I would use router.

When the user moves from homepage to other page, you don't need to fetch new items, just choose the needed items (3 items) and render it.

Upvotes: 0

Balaji
Balaji

Reputation: 1019

The Backbone collection (Doc : http://backbonejs.org/#Collection) is a set of models.

Its best to use a backbone collection when you are dealing with data that is used to populate UI components like data gird / table, data lists e.t.c were you need a set of data.

MyApp.collections.ItemCollection = Backbone.Collection.extend({
    model: Item,
    url: "getItems"
});

The model attribute inside the collection specifies the type of data the is present in the collection. The collection uses this information to efficiently manage data inside it (merge during server fetch for already existing models /can pass raw json data to methods like add).

Using the collection fetch method(http://backbonejs.org/#Collection-fetch), data is fetched from the server.

var itemCollection = new MyApp.collections.ItemCollection();
itemCollection.fetch({
   // The data property is used to send input data to the server method.
   // Any data that will be required by the server method can be passed using this.
    data: {
        limit : 5
    },
    success : function(collection, response, options) {
        //Do your logic
        console.log("Success...");
    }
    error: function(collection, response, options) {
        //Do your logic
    }
});

Upvotes: 1

Related Questions