Question

I've just realized that when you observe the movedTo event on some cursor, the event is only triggered for documents that actually changed their relative position in the resulting set, so not only its index. For example, if the resulting set of documents is first equal to [1, 2, 3], and then it changes to [3, 1, 2], the event will be triggered only for the third document, not all of them. While it sound reasonable from the efficiency point of view, the documentation is not at all clear (look here):

movedTo(document, fromIndex, toIndex, before)

A document changed its position in the result set, from fromIndex to toIndex (which is before the document with id before). Its current contents is document.

To me, "changed it's position in the resulting set, from index to index" sounds more like all three of them changed their position, so in fact:

  • one goes from index 0 to index 1, ...
  • two goes from index 1 to index 2, and ...
  • three goes from index 2 to 0.

What I want to achieve is to observe a cursor and know whether the index of each document changes or not. While I have some rough idea how to implement this, I am wondering if there is a simple (optimal?) and "Meteor friendly" way to solve this problem.

Was it helpful?

Solution

This behavior actually makes perfect sense not only from performance point of view. Think about it that way:

When you use observe method, you want to be notified of all changes that happen to the collection (whether on the server or in minimongo). So each of the callbacks you receive is a single instance of modification of the collection. When you change order of objects by moving one of them to another place, you change the collection once, so you want to receive just one callback for this event.

You don't want to be notified 42 times about a single event!

 


 

I think the easiest way to multiply that notification for all moved objects is to loop over them manually within the callback. When an item moves from position A to position B, you know that all objects that were between A and B have also been shifted. So if you need to adjust each of them, simply do this in loop that goes from A to B over the whole list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top