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