3gwebtrain
3gwebtrain

Reputation: 15299

How can i sort after i done the fetch in backone.js

On click of the 'sort by age', i am calling a function to fetch data from server and sort by age value. i do this after i done the fetching, but it result nothing and return all..

any one give a correct way to implement this?

my code:

this code in the view class,

 sortByAge:function(){
        this.collection.fetch() //fetching new collection
        .done(function(data){ // once done i am passing data
            var filterType = data.sort('age') // correct way need to sort.
            that.collection.reset(filterType); // refreshing the collection
        })
    },

Upvotes: 1

Views: 2650

Answers (1)

Cyclone
Cyclone

Reputation: 1580

If before doing a fetch you're already aware that you need collection to be sorted by some specific column, from the docs, we can pass ajax options to the fetch. So fetch might look like this:

this.collection.fetch({
  data: {
    sort_by: "age"
  }
});

sort_by parameter will be available in the server code being executed at the specified url for the collection, so you can return data from the server sorted by sort_by column. And then may be listen to reset event to do some work.

And if you want to sort collection after getting it on the client side may be you can look at these similar questions.

  1. Sorting a Backbone Collection After initialization
  2. Proper way to sort a backbone.js collection on the fly

Upvotes: 3

Related Questions