Is it possible to sort a collection only once and then keep this order unchanged, despite reactivity?

I have a list of comments. These comments have the attribute "vote" (users can vote for comments) and they are initially sorted by vote (descending, onRender).

Now that users are voting, the order of comments is being updated to reflect new votes.

Is it possible in any way to keep the original sort order intact? I would like to avoid confusing the user with comments that automatically reorder while he / she is on the page.

Is there a good way to solve this problem? I thought, perhaps, a one-time sort when rendering a page or somehow preserving the order, and then re-applying it whenever the collection is actively updated.

+4
source share
3 answers

You can use the function to sort the Minimongo request. So something like:

const initialVotes = new Map();
Comments.find({}, {sort: (a, b) => {
  if (!initialVotes.has(a._id)) initialVotes.set(a._id, a.votes);
  if (!initialVotes.has(b._id)) initialVotes.set(b._id, b.votes);

  return initialVotes.get(b._id) - initialVotes.get(a._id);
});

This will make comments sorted by original votes. If something else changes (for example, the user edits the comments), it will be reactively distributed; if a new comment is made, it will be reactively added. But if the votes change, the order will not change (but the number of votes that can be cast will be updated).

+4

, , Meteor.call() , , @sdybskiy. , .

onCreated() , :

let voteCursor = Votes.find({commentIds: comments});
    voteCursor.observe({
        added: function(newDocument, oldDocument) {
            // the published vote would have a commentId, so here you
            // would go to your client store for the comments, find the 
            // comment, and increment the count
        },
        removed: function(oldDocument) {
            // same idea here, but process a vote being removed
        }
    });

, , , .

+1

reactive: false, :

Comments.find({},{sort: {vote: -1}, reactive: false});

, . , , . , .

, , , ? : ( Blaze) !

Template.myTemplate.helpers({
  currentVote(){
    return Comments.findOne(this._id).vote;
  }
});

.

+1

Source: https://habr.com/ru/post/1668946/


All Articles