-
Notifications
You must be signed in to change notification settings - Fork 6
/
async-filter.js
61 lines (49 loc) · 2.11 KB
/
async-filter.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
'use strict';
(function (angular) {
function asyncFilter() {
var values = {};
var subscriptions = {};
function async(input, scope) {
// Make sure we have an Observable or a Promise
if (!input || !(input.subscribe || input.then)) {
return input;
}
var inputId = objectId(input);
if (!(inputId in subscriptions)) {
var subscriptionStrategy = input.subscribe && input.subscribe.bind(input) || input.success && input.success.bind(input) // To make it work with HttpPromise
|| input.then.bind(input);
subscriptions[inputId] = subscriptionStrategy(function (value) {
values[inputId] = value;
if (scope && scope.$applyAsync) {
scope.$applyAsync(); // Automatic safe apply, if scope provided
}
});
if (scope && scope.$on) {
// Clean up subscription and its last value when the scope is destroyed.
scope.$on('$destroy', function () {
var sub = subscriptions[inputId];
if (sub) {
sub.unsubscribe && sub.unsubscribe();
sub.dispose && sub.dispose();
}
delete subscriptions[inputId];
delete values[inputId];
});
}
}
return values[inputId];
};
// Need a way to tell the input objects apart from each other (so we only subscribe to them once)
var nextObjectID = 0;
function objectId(obj) {
if (!obj.hasOwnProperty('__asyncFilterObjectID__')) {
obj.__asyncFilterObjectID__ = ++nextObjectID;
}
return obj.__asyncFilterObjectID__;
}
// So that Angular does not cache the return value
async.$stateful = true;
return async;
};
angular.module('asyncFilter', []).filter('async', asyncFilter);
})(angular);