Reputation: 1588
How do I sort or manipulate a data collection that has already rendered?
I have a template helper registered that is defined more or less like:
Template.home.helpers({
posts: function() {
return Posts.find({}, { sort: { createdAt: -1 } });
}
});
Which sorts the posts by the most recent ones appearing first. But I want to implement a functionality that reverses this; displaying the oldest posts first.
What is the MeteorJS way of doing it? Any ideas/help is much appreciated.
Upvotes: 0
Views: 31
Reputation: 640
I would do it using a session variable, like so:
First, set the default to display in descending order:
Template.home.onRendered({
Session.set("displayOrder", -1);
});
Then, define a link somewhere in your html to allow the user to change the order:
<a href="#" id="sort">Change sort order</a>
Then define an event to toggle the sort order on click
Template.home.events({
'click #sort' : function () {
var order = Session.get("displayOrder");
var newOrder = -1 * order;
Session.set("displayOrder", newOrder);
}
});
And then change your helper, like so:
Template.home.helpers({
posts: function() {
var displayOrder = Session.get("displayOrder")
return Posts.find({}, { sort: { createdAt: displayOrder } });
}
});
Upvotes: 1