-
Notifications
You must be signed in to change notification settings - Fork 18
/
paginated_subscription.js
76 lines (61 loc) · 2.01 KB
/
paginated_subscription.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
PaginatedSubscriptionHandle = function(perPage) {
this.perPage = perPage;
this._limit = perPage;
this._limitListeners = new Deps.Dependency();
this._loaded = 0;
this._loadedListeners = new Deps.Dependency();
}
PaginatedSubscriptionHandle.prototype.loaded = function() {
this._loadedListeners.depend();
return this._loaded;
}
PaginatedSubscriptionHandle.prototype.limit = function() {
this._limitListeners.depend();
return this._limit;
}
PaginatedSubscriptionHandle.prototype.ready = function() {
return this.loaded() === this.limit();
}
// deprecated
PaginatedSubscriptionHandle.prototype.loading = function() {
return ! this.ready();
}
PaginatedSubscriptionHandle.prototype.loadNextPage = function() {
this._limit += this.perPage;
this._limitListeners.changed();
}
PaginatedSubscriptionHandle.prototype.done = function() {
this._loaded = this._limit;
this._loadedListeners.changed();
}
PaginatedSubscriptionHandle.prototype.reset = function() {
this._limit = this.perPage;
this._limitListeners.changed();
}
Meteor.subscribeWithPagination = function (/*name, arguments, perPage */) {
var args = Array.prototype.slice.call(arguments, 0);
var lastArg = args.pop();
var perPage, cb = null;
if (_.isFunction(lastArg) || _.isObject(lastArg)) {
cb = lastArg;
perPage = args.pop();
} else {
perPage = lastArg;
}
var handle = new PaginatedSubscriptionHandle(perPage);
var argAutorun = Meteor.autorun(function() {
var ourArgs = _.map(args, function(arg) {
return _.isFunction(arg) ? arg() : arg;
});
var subHandle = Meteor.subscribe.apply(this, ourArgs.concat([handle.limit(), cb]));
// whenever the sub becomes ready, we are done. This may happen right away
// if we are re-subscribing to an already ready subscription.
Meteor.autorun(function() {
if (subHandle.ready())
handle.done();
});
});
// this will stop the subHandle, and the done autorun
handle.stop = _.bind(argAutorun.stop, argAutorun);
return handle;
}