Arnaud Stephan
Arnaud Stephan

Reputation: 401

Change the way a collection is sorted through the client

I have a collection that is shown on a page :

Template.body.helpers({
  chansonsFutures(){
    return Chansons.find({
      "playedStatus":false
    },{
      sort : { score:-1 }
    });
  },
});

And I would like the user to be able to change the way the collection is sorted. In the example it is sorted by score, but how would I go about sorted by something else?

I have a select in place :

  <select id="ordre">
    <option value="shuffle">Aléatoire</option>
    <option value="vote">Vote</option>
    <option value="lastAdded">Dernier Ajout</option>
  </select>

But if I put an if condition in Template.body.helpers, meteor tells my application has errors and is waiting for file changes. If I put the condition in Template.body.events and link it to the change of my select, it also gives me errors.

How should I proceed?

edit : to answer @Justinas, here is how I put the condition in code.

My first try was straight in the helper :

Template.body.helpers({

if(document.getElementById("ordre").value == "lastAdded"){
  chansonsFutures(){
    return Chansons.find({
      "playedStatus":false
    },{
      sort : { lastAdded:-1 }
    });
  },
};

else if (other value for the select) {
    other stuff happens
};
});

And the other way was like this :

Template.body.events({

  'change #ordre'(event){
    event.preventDefault();

    chansonsFutures(){

      return Chansons.find({
        "playedStatus":false
      },{
        sort : { document.getElementById("ordre").value:-1 }
      });
    },
  },
});

Upvotes: 1

Views: 63

Answers (1)

Aman Varshney
Aman Varshney

Reputation: 56

Here it is what you need to add in your js fiile :

By defalult it will sot by 'score' and on changing select value it will change accordingly.

    Template.body.onCreated(function() {
      this.sortBy = new ReactiveVar('score');
    })
    Template.body.helpers({

      chansonsFutures : function(){
        var sortParam = Template.instance().sortBy.get();
        return Chansons.find({
          "playedStatus":false
        },{
          sort : { sortParam:-1 }
        });
      },
    });


 Template.body.events({
       'change #ordre':function (event,templateInstance) {
         var sortSelected = $('#ordre option:selelcted').val();
         templateInstance.sortBy.set(sortSelected)
       }
    })

Upvotes: 2

Related Questions