UNPKG

2.02 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 */
9///
10var EventEmitter = require('events').EventEmitter;
11var LangUtils = require('./utils').LangUtils;
12var applyEachSeries = require('async').applyEachSeries;
13
14
15/**
16 * @classdesc SequentialEventEmitter class is an extension of node.js EventEmitter class where listeners are executing in series.
17 * @class
18 * @constructor
19 * @augments EventEmitter
20 */
21function SequentialEventEmitter() {
22 //
23}
24LangUtils.inherits(SequentialEventEmitter, EventEmitter);
25
26/**
27 * Executes event listeners in series.
28 * @param {String} event - The event that is going to be executed.
29 * @param {...*} args - An object that contains the event arguments.
30 */
31// eslint-disable-next-line no-unused-vars
32SequentialEventEmitter.prototype.emit = function(event, args)
33{
34 //ensure callback
35 callback = callback || function() {};
36 //get listeners
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 //check the last argument (expected callback function)
45 if (typeof argsAndCallback[argsAndCallback.length - 1] !== "function") {
46 throw new TypeError("Expected event callback");
47 }
48 }
49 //get callback function (the last argument of arguments list)
50 var callback = argsAndCallback[argsAndCallback.length - 1];
51
52 //validate listeners
53 if (listeners.length===0) {
54 //exit emitter
55 return callback();
56 }
57 //apply each series
58 return applyEachSeries.apply(this, [listeners].concat(argsAndCallback));
59};
60
61if (typeof exports !== 'undefined') {
62 module.exports.SequentialEventEmitter = SequentialEventEmitter;
63}
\No newline at end of file