forked from balderdashy/sails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathafter.js
96 lines (76 loc) · 2.18 KB
/
after.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* Module dependencies
*/
var _ = require('lodash');
var async = require('async');
//
// TODO
// Pull this into a separate module, since it's not specific to Sails.
//
/**
* Mix-in an `after` function to an EventEmitter.
*
* If `events` have already fired, trigger fn immediately (with no args)
* Otherwise bind a normal one-time event using `EventEmitter.prototype.once()`.
* Useful for checking whether or not something has finished loading, etc.
*
* This is a lot like jQuery's `$(document).ready()`.
*
* @param {EventEmitter} emitter
*/
module.exports = function mixinAfter(emitter) {
/**
* { emitter.warmEvents }
*
* Events which have occurred at least once
* (Required to support `emitter.after()`)
*/
emitter.warmEvents = {};
/**
* emitter.emit()
*
* Override `EventEmitter.prototype.emit`.
* (Required to support `emitter.after()`)
*/
var _emit = _.clone(emitter.emit);
emitter.emit = function(evName) {
var args = Array.prototype.slice.call(arguments, 0);
emitter.warmEvents[evName] = true;
_emit.apply(emitter, args);
};
/**
* `emitter.after()`
*
* Fires your handler **IF THE SPECIFIED EVENT HAS ALREADY BEEN TRIGGERED** or **WHEN IT IS TRIGGERED**.
*
* @param {String|Array} events [name of the event(s)]
* @param {Function} fn [event handler function]
* @context {Sails}
*/
emitter.after = function(events, fn) {
// Support a single event or an array of events
if (!_.isArray(events)) {
events = [events];
}
// Convert named event dependencies into an array
// of async-compatible functions.
var dependencies = _.reduce(events,
function(dependencies, event) {
var handlerFn = function(cb) {
if (emitter.warmEvents[event]) {
cb();
} else {
emitter.once(event, cb);
}
};
dependencies.push(handlerFn);
return dependencies;
}, []);
// When all events have fired, call `fn`
// (all arguments passed to `emit()` calls are discarded)
async.parallel(dependencies, function(err) {
if (err) sails.log.error(err);
return fn();
});
};
};