UNPKG

2.46 kBJavaScriptView Raw
1/**
2 * @license
3 * MOST Web Framework 2.0 Codename Blueshift
4 * Copyright (c) 2017, THEMOST LP All rights reserved
5 *
6 * Use of this source code is governed by an BSD-3-Clause license that can be
7 * found in the LICENSE file at https://themost.io/license
8 */
9var EventEmitter = require('events').EventEmitter;
10var LangUtils = require('./utils').LangUtils;
11var applyEachSeries = require('async').applyEachSeries;
12
13
14/**
15 * @classdesc SequentialEventEmitter class is an extension of node.js EventEmitter class where listeners are executing in series.
16 * @class
17 * @constructor
18 * @augments EventEmitter
19 */
20function SequentialEventEmitter() {
21 //
22}
23LangUtils.inherits(SequentialEventEmitter, EventEmitter);
24
25/**
26 * Executes event listeners in series.
27 * @param {String} event - The event that is going to be executed.
28 * @param {...*} args - An object that contains the event arguments.
29 */
30// eslint-disable-next-line no-unused-vars
31SequentialEventEmitter.prototype.emit = function(event, args)
32{
33 //ensure callback
34 callback = callback || function() {};
35 //get listeners
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 //check the last argument (expected callback function)
44 if (typeof argsAndCallback[argsAndCallback.length - 1] !== "function") {
45 throw new TypeError("Expected event callback");
46 }
47 }
48 //get callback function (the last argument of arguments list)
49 var callback = argsAndCallback[argsAndCallback.length - 1];
50
51 //validate listeners
52 if (listeners.length===0) {
53 //exit emitter
54 return callback();
55 }
56 //apply each series
57 return applyEachSeries.apply(this, [listeners].concat(argsAndCallback));
58};
59
60SequentialEventEmitter.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
78if (typeof exports !== 'undefined') {
79 module.exports.SequentialEventEmitter = SequentialEventEmitter;
80}
\No newline at end of file