-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathng.async.js
More file actions
89 lines (77 loc) · 1.92 KB
/
ng.async.js
File metadata and controls
89 lines (77 loc) · 1.92 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* ng.async
*
* Author : Nate Ferrero
* License: MIT
* Version: 0.0.1
*
* This Angular.js module provides the $async angular service, which allows
* template variables to trigger a function to perform asyncronous operations.
*
* Usage:
*
* $async(scope, {
* var1: function (resolve) { ... },
* var2: function (resolve) { ... }
* });
*
* Alternative:
*
* $async(scope, 'var3', function (resolve) { ... });
*/
(function (angular) {
/**
* Error message if $async is used incorrectly
*/
var usage = 'Usage: $async(scope, {var: function (resolve) { ... }});';
var async;
var module = angular.module('ng.async', []);
/**
* Setup the async wrapper
*/
module.run(function ($q) {
async = function (fn) {
if (typeof fn !== 'function') {
throw new Error(usage);
}
var cache;
var deferred;
/**
* Getter function
* Automatically called once when data is needed
*/
return function () {
if (deferred === undefined) {
deferred = $q.defer();
deferred.promise.then(function (value) {
cache = value;
});
cache = fn(deferred.resolve);
}
return cache;
};
};
});
/**
* $async service
*/
module.value('$async', function (scope, property, fn) {
if (typeof scope !== 'object' || scope === null) {
throw new Error('First argument to $async must be an object');
}
if (typeof property === 'object' && property !== null) {
if (fn !== undefined) {
throw new Error(usage);
}
Object.keys(property).forEach(function (prop) {
scope.__defineGetter__(prop, async(property[prop]));
});
}
else if (typeof property === 'string') {
scope.__defineGetter__(property, async(fn));
}
else {
throw new Error(usage);
}
});
})(angular);