1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | var EventEmitter = require('events').EventEmitter;
|
11 | var LangUtils = require('./utils').LangUtils;
|
12 | var applyEachSeries = require('async').applyEachSeries;
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | function SequentialEventEmitter() {
|
22 |
|
23 | }
|
24 | LangUtils.inherits(SequentialEventEmitter, EventEmitter);
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 | SequentialEventEmitter.prototype.emit = function(event, args)
|
33 | {
|
34 |
|
35 | callback = callback || function() {};
|
36 |
|
37 | if (typeof this.listeners !== 'function') {
|
38 | throw new Error('undefined listeners');
|
39 | }
|
40 | var listeners = this.listeners(event);
|
41 |
|
42 | var argsAndCallback = [].concat(Array.prototype.slice.call(arguments, 1));
|
43 | if (argsAndCallback.length > 0) {
|
44 |
|
45 | if (typeof argsAndCallback[argsAndCallback.length - 1] !== "function") {
|
46 | throw new TypeError("Expected event callback");
|
47 | }
|
48 | }
|
49 |
|
50 | var callback = argsAndCallback[argsAndCallback.length - 1];
|
51 |
|
52 |
|
53 | if (listeners.length===0) {
|
54 |
|
55 | return callback();
|
56 | }
|
57 |
|
58 | return applyEachSeries.apply(this, [listeners].concat(argsAndCallback));
|
59 | };
|
60 |
|
61 | SequentialEventEmitter.prototype.once = function(type, listener) {
|
62 | var self = this;
|
63 | if (typeof listener !== 'function')
|
64 | throw TypeError('listener must be a function');
|
65 | var fired = false;
|
66 | function g() {
|
67 | self.removeListener(type, g);
|
68 | if (!fired) {
|
69 | fired = true;
|
70 | listener.apply(this, arguments);
|
71 | }
|
72 | }
|
73 | g.listener = listener;
|
74 | this.on(type, g);
|
75 | return this;
|
76 | };
|
77 |
|
78 |
|
79 | if (typeof exports !== 'undefined') {
|
80 | module.exports.SequentialEventEmitter = SequentialEventEmitter;
|
81 | } |
\ | No newline at end of file |