-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathobserve-cursor.js
37 lines (34 loc) · 1.35 KB
/
observe-cursor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { Tracker } from 'meteor/tracker';
import { action } from 'mobx';
export default (actionPrefix = '', observableArray, handle, cursor) => {
if (handle.ready()) {
// initially fetch all documents and store them in the observable array
Tracker.nonreactive(() => {
action(`${actionPrefix}: initial fetch`, (comments) => {
observableArray.replace(comments);
})(cursor.fetch());
});
// observe changes after initial fetch
cursor.observe({
// _suppress_initial suppresses addedAt callback for documents initially fetched
_suppress_initial: true,
addedAt: action(`${actionPrefix}: document added`, (document, atIndex) => {
observableArray.splice(atIndex, 0, document);
}),
changedAt: action(`${actionPrefix}: document changed`, (newDocument, oldDocument, atIndex) => {
observableArray.splice(atIndex, 1, newDocument);
}),
removedAt: action(`${actionPrefix}: document removed`, (oldDocument, atIndex) => {
observableArray.splice(atIndex, 1);
}),
movedTo: action(`${actionPrefix}: document moved`, (document, fromIndex, toIndex) => {
observableArray.splice(fromIndex, 1);
observableArray.splice(toIndex, 0, document);
}),
});
} else {
action(`${actionPrefix}: initialized`, () => {
observableArray.clear();
})();
}
};