From 69c8fa2a92cd6566543da7e5615d2b3bf29a323e Mon Sep 17 00:00:00 2001 From: Gerkin Date: Mon, 30 Oct 2017 23:02:22 +0100 Subject: [PATCH] 0.3.0 --- dist/sequential-event.js | 68 +++++++++----- dist/sequential-event.js.map | 2 +- dist/sequential-event.min.js | 6 +- docs/SequentialEvent.html | 2 +- docs/classes.list.html | 2 +- docs/index.html | 26 ++++-- docs/quicksearch.html | 2 +- npm-shrinkwrap.json | 2 +- package.json | 2 +- test/browser/index-es5.js | 172 +++++++++++++++++++++++++++++++++++ test/browser/index.js | 172 +++++++++++++++++++++++++++++++++++ 11 files changed, 416 insertions(+), 40 deletions(-) diff --git a/dist/sequential-event.js b/dist/sequential-event.js index f0402fe..5ff11b6 100644 --- a/dist/sequential-event.js +++ b/dist/sequential-event.js @@ -2,10 +2,10 @@ * @file sequential-event * * This library is a variation of standard event emitters. Handlers are executed sequentialy, and may return Promises if it executes asynchronous code -* Built on 2017-10-30 19:51:06 +* Built on 2017-10-30 23:02:09 * * @license GPL-3.0 -* @version 0.2.0 +* @version 0.3.0 * @author Gerkin */ var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); @@ -14,6 +14,8 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + (function (f) { if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === "object" && typeof module !== "undefined") { module.exports = f(); @@ -88,11 +90,15 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons */ var getNextPromise = function getNextPromise(handlers, object, args) { - //(resolve, reject) => { var i = 0; var handlersLength = handlers.length; return function (resolve, reject) { var _getNextPromise = function _getNextPromise(prevResolve) { + var handlersLength2 = handlers.length; + if (handlersLength2 !== handlersLength) { + i -= handlersLength - handlersLength2; + handlersLength = handlersLength2; + } if (i < handlersLength) { var stepArgs = 'undefined' !== typeof prevResolve ? args.concat([prevResolve]) : args.slice(0); var newPromise = emitHandler(handlers[i], object, stepArgs); @@ -143,14 +149,15 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons */ var onceify = function onceify(target, eventName, eventFn) { var called = false; - var fn = function fn() { + var once = function once() { if (!called) { - target.off(eventName, fn); + target.off(eventName, once); called = true; return eventFn.apply(undefined, arguments); } }; - return fn; + once.origFn = eventFn; + return once; }; /** @@ -164,8 +171,13 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons * @inner */ var removeEventListener = function removeEventListener(eventCat, callback) { - var index = eventCat.indexOf(callback); - if (index !== -1) { + var indexes = [eventCat.indexOf(callback), eventCat.findIndex(function (elem) { + return elem.origFn === callback; + })]; + var index = Math.min.apply(Math, _toConsumableArray(indexes.filter(function (v) { + return v >= 0; + }))); + if (isFinite(index)) { eventCat.splice(index, 1); } }; @@ -182,8 +194,7 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons * @inner */ var addEventListener = function addEventListener(eventHash, eventName, callback) { - eventHash[eventName] = eventHash[eventName] || []; - eventHash[eventName].push(callback); + eventHash[eventName] = ensureArray(eventHash[eventName]).concat(ensureArray(callback)); }; /** @@ -208,6 +219,13 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons } }; + var ensureArray = function ensureArray(data) { + if ('undefined' === typeof data) { + return []; + } + return Array === data.constructor ? data : [data]; + }; + /** * Event emitter that guarantees sequential execution of handlers. Each handler may return a **Promise**. * @@ -240,9 +258,6 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons key: "emit", value: function emit(type) { var events = this.__events; - if (!events) { - return Promise.resolve(); - } var handler = events[type]; if (!handler) { @@ -278,13 +293,12 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons var eventsObj = castToEventObject(events, callback); for (var event in eventsObj) { - if (!eventsObj.hasOwnProperty(event)) { - continue; - } - if (eventsObj[event]) { - removeEventListener(_events[event], eventsObj[event]); - } else { - _events[event] = []; + if (eventsObj.hasOwnProperty(event)) { + if (eventsObj[event]) { + removeEventListener(_events[event], eventsObj[event]); + } else { + _events[event] = []; + } } } return this; @@ -301,13 +315,23 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons }, { key: "once", value: function once(events, callback) { + var _this = this; + var _events = this.__events; var eventsObj = castToEventObject(events, callback); - for (var event in eventsObj) { + + var _loop = function _loop(event) { if (eventsObj.hasOwnProperty(event)) { - addEventListener(_events, event, onceify(this, event, eventsObj[event])); + var _events2 = ensureArray(eventsObj[event]); + _events2.forEach(function (eventHandler) { + addEventListener(_events, event, onceify(_this, event, eventHandler)); + }); } + }; + + for (var event in eventsObj) { + _loop(event); } return this; diff --git a/dist/sequential-event.js.map b/dist/sequential-event.js.map index dbd7644..cff495f 100644 --- a/dist/sequential-event.js.map +++ b/dist/sequential-event.js.map @@ -1 +1 @@ -{"version":3,"sources":["sequential-event.js"],"names":["f","exports","module","define","amd","g","window","global","self","SequentialEvent","e","t","n","r","s","o","u","a","require","i","Error","code","l","call","length","emitHandlers","handlers","object","args","emitHandler","promiseGen","getNextPromise","sourcePromise","Promise","handlersLength","resolve","reject","_getNextPromise","prevResolve","stepArgs","concat","slice","newPromise","then","catch","handler","retVal","apply","onceify","target","eventName","eventFn","called","fn","off","removeEventListener","eventCat","callback","index","indexOf","splice","addEventListener","eventHash","push","castToEventObject","events","eventsObj","split","forEach","event","__events","type","retPromise","_events","hasOwnProperty"],"mappings":";;;;;;;;;;;;;;;;AAAA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,EAAwC;AACvCR,yBAAkBY,OAAlB,EAA2BJ,KAA3B,EAAkCrB,QAAS,IAAT,EAAeqB,KAAf,EAAsBH,UAAUG,KAAV,CAAtB,CAAlC;AACA;AACD;;AAED,aAAO,IAAP;AACA;;AAED;;;;;;;;AA5Pq1B;AAAA;AAAA,wBAmQj1BJ,MAnQi1B,EAmQz0BR,QAnQy0B,EAmQ9zB;AACtB,UAAMgB,UAAU,KAAKH,QAArB;;AAEA,UAAMJ,YAAYF,kBAAmBC,MAAnB,EAA2BR,QAA3B,CAAlB;AACA,WAAM,IAAMY,KAAZ,IAAqBH,SAArB,EAAiC;AAChC,WAAKA,UAAUQ,cAAV,CAA0BL,KAA1B,CAAL,EAAwC;AACvCR,yBAAkBY,OAAlB,EAA2BJ,KAA3B,EAAkCH,UAAUG,KAAV,CAAlC;AACA;AACD;;AAED,aAAO,IAAP;AACA;AA9Qo1B;;AAAA;AAAA;;AAiRt1BnE,UAAOD,OAAP,GAAiBQ,eAAjB;AAEC,GAnRozB,EAmRnzB,EAnRmzB,CAAH,EAA3b,EAmRhX,EAnRgX,EAmR7W,CAAC,CAAD,CAnR6W,EAmRxW,CAnRwW,CAAP;AAoR/W,CApRD","file":"sequential-event.js","sourcesContent":["(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.SequentialEvent = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o {\n\t// Check if the provided handler is a single function or an array of functions\n\tif ( 'function' === typeof handlers ) {\n\t\treturn emitHandler( handlers, object, args );\n\t} else {\n\t\tconst promiseGen = getNextPromise( handlers, object, args );\n\t\tconst sourcePromise = new Promise( promiseGen );\n\t\treturn sourcePromise;\n\t}\n};\n\n/**\n * Generate next promise for sequence.\n *\n * @param {Function|Function[]} handlers - Function(s) to execute. Each function may return a Promise.\n * @param {SequentialEvent} object - Objecto call event on.\n * @param {Any[]} [args] - Arguments to pass to each called function.\n * @returns {Function} Promise handler.\n * @memberof SequentialEvent\n * @author Gerkin\n * @inner\n */\n\nconst getNextPromise = ( handlers, object, args ) => { //(resolve, reject) => {\n\tlet i = 0;\n\tconst handlersLength = handlers.length;\n\treturn ( resolve, reject ) => {\n\t\tconst _getNextPromise = ( prevResolve ) => {\n\t\t\tif ( i < handlersLength ) {\n\t\t\t\tconst stepArgs = 'undefined' !== typeof prevResolve ? args.concat([ prevResolve ]) : args.slice( 0 );\n\t\t\t\tconst newPromise = emitHandler( handlers[i], object, stepArgs );\n\t\t\t\tnewPromise.then( _getNextPromise ).catch( reject );\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\treturn resolve.call( null, prevResolve );\n\t\t\t}\n\t\t};\n\t\treturn _getNextPromise();\n\t};\n};\n\n/**\n * Handle execution of a single handler.\n *\n * @param {Function} handler - Function to execute. It may return a Promise.\n * @param {SequentialEvent} object - Object to call event on.\n * @param {Any[]} [args] - Arguments to pass to each called function.\n * @returns {Promise} Promise resolved once this function is done.\n * @memberof SequentialEvent\n * @author Gerkin\n * @inner\n */\nconst emitHandler = ( handler, object, args ) => {\n\ttry {\n\t\tconst retVal = handler.apply( object, args );\n\t\tif ( 'object' === typeof retVal && 'function' === typeof retVal.then ) {\n\t\t\treturn retVal;\n\t\t} else {\n\t\t\treturn Promise.resolve( retVal );\n\t\t}\n\t} catch ( e ) {\n\t\treturn Promise.reject( e );\n\t}\n};\n\n/**\n * Generate an event handler that deregister itself when executed. This handler will be executed just once.\n *\n * @param {Object} target - Event emitter that will use the handler.\n * @param {string} eventName - Name of the event to trigger.\n * @param {Function} eventFn - Handler for the event.\n * @returns {Function} Function that will be executed only once.\n * @memberof SequentialEvent\n * @author Gerkin\n * @inner\n */\nconst onceify = ( target, eventName, eventFn ) => {\n\tlet called = false;\n\tconst fn = ( ...args ) => {\n\t\tif ( !called ) {\n\t\t\ttarget.off( eventName, fn );\n\t\t\tcalled = true;\n\t\t\treturn eventFn( ...args );\n\t\t}\n\t};\n\treturn fn;\n};\n\n/**\n * Remove provided `callback` from listeners of event `eventCat`.\n *\n * @param {Function[]} eventCat - Array of listeners to remove callback from.\n * @param {Function} [callback] - Callback to remove.\n * @returns {undefined} This function does not returns anything.\n * @memberof SequentialEvent\n * @author Gerkin\n * @inner\n */\nconst removeEventListener = ( eventCat, callback ) => {\n\tconst index = eventCat.indexOf( callback );\n\tif ( index !== -1 ) {\n\t\teventCat.splice( index, 1 );\n\t}\n};\n\n\n/**\n * Add an event listener to the provided event hash.\n *\n * @param {Object} eventHash - Hash of events of the object. It is usually retrieved from `object.__events`.\n * @param {string} eventName - Name of the event to add listener on.\n * @param {Function} [callback] - Callback to add.\n * @returns {undefined} This function does not returns anything.\n * @memberof SequentialEvent\n * @author Gerkin\n * @inner\n */\nconst addEventListener = ( eventHash, eventName, callback ) => {\n\teventHash[eventName] = eventHash[eventName] || [];\n\teventHash[eventName].push( callback );\n};\n\n/**\n * Ensure that event & callback are on the associative hash format.\n *\n * @param {Object|string} events - Events to cast in hash form.\n * @param {Function} callback - Function to associate with those events.\n * @returns {Object} Events in hash format.\n * @memberof SequentialEvent\n * @author Gerkin\n * @inner\n */\nconst castToEventObject = ( events, callback ) => {\n\tif ( 'object' !== typeof events ) {\n\t\tconst eventsObj = {};\n\t\tevents.split( ' ' ).forEach( event => {\n\t\t\teventsObj[event] = callback;\n\t\t});\n\t\treturn eventsObj;\n\t} else {\n\t\treturn events;\n\t}\n};\n\n/**\n * Event emitter that guarantees sequential execution of handlers. Each handler may return a **Promise**.\n *\n * @see {@link https://nodejs.org/api/events.html Node EventEmitter}.\n */\nclass SequentialEvent {\n\t/**\n\t * Constructs a new SequentialEvent.\n\t *\n\t * @author Gerkin\n\t */\n\tconstructor() {\n\t\tthis.__events = {};\n\t}\n\n\t/**\n\t * Triggers each corresponding handlers in sequence.\n\t *\n\t * @param {Any} type - Name of the event to sequential-event.\n\t * @param {Any[]} [args] - Parameters to pass to handlers.\n\t * @returns {Promise} Returns a Promise resolved when then chain is done.\n\t * @author Gerkin\n\t */\n\temit( type, ...args ) {\n\t\tconst events = this.__events;\n\t\tif ( !events ) {\n\t\t\treturn Promise.resolve();\n\t\t}\n\n\t\tconst handler = events[type];\n\t\tif ( !handler ) {\n\t\t\treturn Promise.resolve();\n\t\t}\n\n\t\tconst retPromise = emitHandlers( handler, this, args );\n\n\t\treturn retPromise;\n\t}\n\n\t/**\n\t * Remove one or many or all event handlers.\n\t *\n\t * @param {string|Object} [events] - Event name or hash of events.\n\t * @param {Function} [callback] - If provided an event name with `events`, function to associate with the event.\n\t * @returns {SequentialEvent} Returns `this`.\n\t */\n\toff( events, callback ) {\n\t\tconst _events = this.__events;\n\n\t\tif ( !events ) {\n\t\t\tthis.__events = {};\n\t\t\treturn this;\n\t\t}\n\n\t\tconst eventsObj = castToEventObject( events, callback );\n\t\tfor ( const event in eventsObj ) {\n\t\t\tif ( !eventsObj.hasOwnProperty( event )) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ( eventsObj[event]) {\n\t\t\t\tremoveEventListener( _events[event], eventsObj[event]);\n\t\t\t} else {\n\t\t\t\t_events[event] = [];\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add one or many event handlers that will be called only once.\n\t *\n\t * @param {string|Object} events - Event name or hash of events.\n\t * @param {Function} [callback] - If provided an event name with `events`, function to associate with the event.\n\t * @returns {SequentialEvent} Returns `this`.\n\t */\n\tonce( events, callback ) {\n\t\tconst _events = this.__events;\n\n\t\tconst eventsObj = castToEventObject( events, callback );\n\t\tfor ( const event in eventsObj ) {\n\t\t\tif ( eventsObj.hasOwnProperty( event )) {\n\t\t\t\taddEventListener( _events, event, onceify( this, event, eventsObj[event]));\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add one or many event handlers.\n\t *\n\t * @param {string|Object} events - Event name or hash of events.\n\t * @param {Function} [callback] - If provided an event name with `events`, function to associate with the event.\n\t * @returns {SequentialEvent} Returns `this`.\n\t */\n\ton( events, callback ) {\n\t\tconst _events = this.__events;\n\n\t\tconst eventsObj = castToEventObject( events, callback );\n\t\tfor ( const event in eventsObj ) {\n\t\t\tif ( eventsObj.hasOwnProperty( event )) {\n\t\t\t\taddEventListener( _events, event, eventsObj[event]);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n}\n\nmodule.exports = SequentialEvent;\n\n},{}]},{},[1])(1)\n});"]} \ No newline at end of file +{"version":3,"sources":["sequential-event.js"],"names":["f","exports","module","define","amd","g","window","global","self","SequentialEvent","e","t","n","r","s","o","u","a","require","i","Error","code","l","call","length","emitHandlers","handlers","object","args","emitHandler","promiseGen","getNextPromise","sourcePromise","Promise","handlersLength","resolve","reject","_getNextPromise","prevResolve","handlersLength2","stepArgs","concat","slice","newPromise","then","catch","handler","retVal","apply","onceify","target","eventName","eventFn","called","once","off","origFn","removeEventListener","eventCat","callback","indexes","indexOf","findIndex","elem","index","Math","min","filter","v","isFinite","splice","addEventListener","eventHash","ensureArray","castToEventObject","events","eventsObj","split","forEach","event","data","Array","constructor","__events","type","retPromise","_events","hasOwnProperty","eventHandler"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,CAAC,UAASA,CAAT,EAAW;AAAC,KAAG,QAAOC,OAAP,yCAAOA,OAAP,OAAiB,QAAjB,IAA2B,OAAOC,MAAP,KAAgB,WAA9C,EAA0D;AAACA,SAAOD,OAAP,GAAeD,GAAf;AAAmB,EAA9E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ential-event.js","sourcesContent":["(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.SequentialEvent = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o {\n\t// Check if the provided handler is a single function or an array of functions\n\tif ( 'function' === typeof handlers ) {\n\t\treturn emitHandler( handlers, object, args );\n\t} else {\n\t\tconst promiseGen = getNextPromise( handlers, object, args );\n\t\tconst sourcePromise = new Promise( promiseGen );\n\t\treturn sourcePromise;\n\t}\n};\n\n/**\n * Generate next promise for sequence.\n *\n * @param {Function|Function[]} handlers - Function(s) to execute. Each function may return a Promise.\n * @param {SequentialEvent} object - Objecto call event on.\n * @param {Any[]} [args] - Arguments to pass to each called function.\n * @returns {Function} Promise handler.\n * @memberof SequentialEvent\n * @author Gerkin\n * @inner\n */\n\nconst getNextPromise = ( handlers, object, args ) => {\n\tlet i = 0;\n\tlet handlersLength = handlers.length;\n\treturn ( resolve, reject ) => {\n\t\tconst _getNextPromise = ( prevResolve ) => {\n\t\t\tconst handlersLength2 = handlers.length;\n\t\t\tif ( handlersLength2 !== handlersLength ) {\n\t\t\t\ti -= handlersLength - handlersLength2;\n\t\t\t\thandlersLength = handlersLength2;\n\t\t\t}\n\t\t\tif ( i < handlersLength ) {\n\t\t\t\tconst stepArgs = 'undefined' !== typeof prevResolve ? args.concat([ prevResolve ]) : args.slice( 0 );\n\t\t\t\tconst newPromise = emitHandler( handlers[i], object, stepArgs );\n\t\t\t\tnewPromise.then( _getNextPromise ).catch( reject );\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\treturn resolve.call( null, prevResolve );\n\t\t\t}\n\t\t};\n\t\treturn _getNextPromise();\n\t};\n};\n\n/**\n * Handle execution of a single handler.\n *\n * @param {Function} handler - Function to execute. It may return a Promise.\n * @param {SequentialEvent} object - Object to call event on.\n * @param {Any[]} [args] - Arguments to pass to each called function.\n * @returns {Promise} Promise resolved once this function is done.\n * @memberof SequentialEvent\n * @author Gerkin\n * @inner\n */\nconst emitHandler = ( handler, object, args ) => {\n\ttry {\n\t\tconst retVal = handler.apply( object, args );\n\t\tif ( 'object' === typeof retVal && 'function' === typeof retVal.then ) {\n\t\t\treturn retVal;\n\t\t} else {\n\t\t\treturn Promise.resolve( retVal );\n\t\t}\n\t} catch ( e ) {\n\t\treturn Promise.reject( e );\n\t}\n};\n\n/**\n * Generate an event handler that deregister itself when executed. This handler will be executed just once.\n *\n * @param {Object} target - Event emitter that will use the handler.\n * @param {string} eventName - Name of the event to trigger.\n * @param {Function} eventFn - Handler for the event.\n * @returns {Function} Function that will be executed only once.\n * @memberof SequentialEvent\n * @author Gerkin\n * @inner\n */\nconst onceify = ( target, eventName, eventFn ) => {\n\tlet called = false;\n\tconst once = function once( ...args ) {\n\t\tif ( !called ) {\n\t\t\ttarget.off( eventName, once );\n\t\t\tcalled = true;\n\t\t\treturn eventFn( ...args );\n\t\t}\n\t};\n\tonce.origFn = eventFn;\n\treturn once;\n};\n\n/**\n * Remove provided `callback` from listeners of event `eventCat`.\n *\n * @param {Function[]} eventCat - Array of listeners to remove callback from.\n * @param {Function} [callback] - Callback to remove.\n * @returns {undefined} This function does not returns anything.\n * @memberof SequentialEvent\n * @author Gerkin\n * @inner\n */\nconst removeEventListener = ( eventCat, callback ) => {\n\tconst indexes = [ eventCat.indexOf( callback ), eventCat.findIndex( elem => elem.origFn === callback ) ];\n\tconst index = Math.min( ...indexes.filter( v => v >= 0 ));\n\tif ( isFinite( index )) {\n\t\teventCat.splice( index, 1 );\n\t}\n};\n\n\n/**\n * Add an event listener to the provided event hash.\n *\n * @param {Object} eventHash - Hash of events of the object. It is usually retrieved from `object.__events`.\n * @param {string} eventName - Name of the event to add listener on.\n * @param {Function} [callback] - Callback to add.\n * @returns {undefined} This function does not returns anything.\n * @memberof SequentialEvent\n * @author Gerkin\n * @inner\n */\nconst addEventListener = ( eventHash, eventName, callback ) => {\n\teventHash[eventName] = ensureArray( eventHash[eventName]).concat( ensureArray( callback ));\n};\n\n/**\n * Ensure that event & callback are on the associative hash format.\n *\n * @param {Object|string} events - Events to cast in hash form.\n * @param {Function} callback - Function to associate with those events.\n * @returns {Object} Events in hash format.\n * @memberof SequentialEvent\n * @author Gerkin\n * @inner\n */\nconst castToEventObject = ( events, callback ) => {\n\tif ( 'object' !== typeof events ) {\n\t\tconst eventsObj = {};\n\t\tevents.split( ' ' ).forEach( event => {\n\t\t\teventsObj[event] = callback;\n\t\t});\n\t\treturn eventsObj;\n\t} else {\n\t\treturn events;\n\t}\n};\n\nconst ensureArray = data => {\n\tif ( 'undefined' === typeof data ) {\n\t\treturn [];\n\t}\n\treturn Array === data.constructor ? data : [ data ];\n};\n\n/**\n * Event emitter that guarantees sequential execution of handlers. Each handler may return a **Promise**.\n *\n * @see {@link https://nodejs.org/api/events.html Node EventEmitter}.\n */\nclass SequentialEvent {\n\t/**\n\t * Constructs a new SequentialEvent.\n\t *\n\t * @author Gerkin\n\t */\n\tconstructor() {\n\t\tthis.__events = {};\n\t}\n\n\t/**\n\t * Triggers each corresponding handlers in sequence.\n\t *\n\t * @param {Any} type - Name of the event to sequential-event.\n\t * @param {Any[]} [args] - Parameters to pass to handlers.\n\t * @returns {Promise} Returns a Promise resolved when then chain is done.\n\t * @author Gerkin\n\t */\n\temit( type, ...args ) {\n\t\tconst events = this.__events;\n\n\t\tconst handler = events[type];\n\t\tif ( !handler ) {\n\t\t\treturn Promise.resolve();\n\t\t}\n\n\t\tconst retPromise = emitHandlers( handler, this, args );\n\n\t\treturn retPromise;\n\t}\n\n\t/**\n\t * Remove one or many or all event handlers.\n\t *\n\t * @param {string|Object} [events] - Event name or hash of events.\n\t * @param {Function} [callback] - If provided an event name with `events`, function to associate with the event.\n\t * @returns {SequentialEvent} Returns `this`.\n\t */\n\toff( events, callback ) {\n\t\tconst _events = this.__events;\n\n\t\tif ( !events ) {\n\t\t\tthis.__events = {};\n\t\t\treturn this;\n\t\t}\n\n\t\tconst eventsObj = castToEventObject( events, callback );\n\t\tfor ( const event in eventsObj ) {\n\t\t\tif ( eventsObj.hasOwnProperty( event )) {\n\t\t\t\tif ( eventsObj[event]) {\n\t\t\t\t\tremoveEventListener( _events[event], eventsObj[event]);\n\t\t\t\t} else {\n\t\t\t\t\t_events[event] = [];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add one or many event handlers that will be called only once.\n\t *\n\t * @param {string|Object} events - Event name or hash of events.\n\t * @param {Function} [callback] - If provided an event name with `events`, function to associate with the event.\n\t * @returns {SequentialEvent} Returns `this`.\n\t */\n\tonce( events, callback ) {\n\t\tconst _events = this.__events;\n\n\t\tconst eventsObj = castToEventObject( events, callback );\n\t\tfor ( const event in eventsObj ) {\n\t\t\tif ( eventsObj.hasOwnProperty( event )) {\n\t\t\t\tconst events = ensureArray( eventsObj[event]);\n\t\t\t\tevents.forEach( eventHandler => {\n\t\t\t\t\taddEventListener( _events, event, onceify( this, event, eventHandler ));\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add one or many event handlers.\n\t *\n\t * @param {string|Object} events - Event name or hash of events.\n\t * @param {Function} [callback] - If provided an event name with `events`, function to associate with the event.\n\t * @returns {SequentialEvent} Returns `this`.\n\t */\n\ton( events, callback ) {\n\t\tconst _events = this.__events;\n\n\t\tconst eventsObj = castToEventObject( events, callback );\n\t\tfor ( const event in eventsObj ) {\n\t\t\tif ( eventsObj.hasOwnProperty( event )) {\n\t\t\t\taddEventListener( _events, event, eventsObj[event]);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n}\n\nmodule.exports = SequentialEvent;\n\n},{}]},{},[1])(1)\n});"]} \ No newline at end of file diff --git a/dist/sequential-event.min.js b/dist/sequential-event.min.js index abca7c1..7f2a684 100644 --- a/dist/sequential-event.min.js +++ b/dist/sequential-event.min.js @@ -2,10 +2,10 @@ * @file sequential-event * * This library is a variation of standard event emitters. Handlers are executed sequentialy, and may return Promises if it executes asynchronous code -* Built on 2017-10-30 19:51:06 +* Built on 2017-10-30 23:02:09 * * @license GPL-3.0 -* @version 0.2.0 +* @version 0.3.0 * @author Gerkin */ -function _classCallCheck(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function e(e,n){for(var t=0;t1?o-1:0),f=1;f=0})));isFinite(t)&&n.splice(t,1)},a=function(n,e,r){n[e]=s(n[e]).concat(s(r))},c=function(n,e){if("object"!==(void 0===n?"undefined":_typeof(n))){var r={};return n.split(" ").forEach(function(n){r[n]=e}),r}return n},s=function(n){return void 0===n?[]:Array===n.constructor?n:[n]},l=function(){function n(){_classCallCheck(this,n),this.__events={}}return _createClass(n,[{key:"emit",value:function(n){var e=this.__events[n];if(!e)return Promise.resolve();for(var r=arguments.length,o=Array(r>1?r-1:0),i=1;iSearch results Documentation generated by JSDoc 3.5.5 - on 2017-10-30T19:51:10+01:00 + on 2017-10-30T23:02:18+01:00 using the DocStrap template. diff --git a/docs/classes.list.html b/docs/classes.list.html index 49168ac..8d31fac 100644 --- a/docs/classes.list.html +++ b/docs/classes.list.html @@ -195,7 +195,7 @@ Documentation generated by JSDoc 3.5.5 - on 2017-10-30T19:51:10+01:00 + on 2017-10-30T23:02:18+01:00 using the DocStrap template. diff --git a/docs/index.html b/docs/index.html index 0f059c5..78b25c8 100644 --- a/docs/index.html +++ b/docs/index.html @@ -98,7 +98,8 @@

See the API documentation on github.io/SequentialEvent.js

-

This library is a variation of standard event emitters. Handlers are executed sequentialy, and may return Promises if it executes asynchronous code.

+

This library is a variation of standard event emitters. Handlers are executed +sequentialy, and may return Promises if it executes asynchronous code.

For usage in the browser, use the files in the dist directory

Example usage

const SequentialEvent = require( 'sequential-event' );
 
@@ -113,7 +114,8 @@ 

Example usage

cons
 });
 // We wait 100ms and we re-time
 eventEmitter.on( 'retime', ( startTime, timers ) => {
-    // This operation is async, so we return a Promise that will be resolved with the timers array
+    // This operation is async, so we return a Promise that will be resolved
+    // with the timers array
     return new Promise(( resolve ) => {
         setTimeout(() => {
             timers.push( sampleTime( startTime ));
@@ -133,12 +135,15 @@ 

Example usage

cons
     .emit( 'retime', new Date().getTime())
     // Log normaly if everything is OK, or log with error
     .then( timers => console.log( timers ))
-    .catch( err => console.error( err ));

Sample output

+ .catch( err => console.error( err ));

Here is an example of output of this code:

[ 1, 109, 109 ]

-

You can see that each on handlers are executed sequentially, after the end of the previous handler.

-

API

emit

Triggers all listeners of the provided events, spraying params to each callbacks. Returned or resolved values from callbacks (if returning a Promise) are passed as last parameter of the next callback function.

+

You can see that each on handlers are executed sequentially, after the end of +the previous handler.

+

API

emit

Triggers all listeners of the provided events, spraying params to each +callbacks. Returned or resolved values from callbacks (if returning a +Promise) are passed as last parameter of the next callback function.

Signature:

emit(string eventName[, ...any params]) => Promise(any)

@@ -158,15 +163,18 @@

off

Remove callbacks from events.

eventListener.off({ event1: cbFoo, event2: cbBar, -});

once

Bind callbacks to specified events. The callback will be executable a single time for each event.

+});

once

Bind callbacks to specified events. The callback will be executable a single +time for each event.

Signatures:

once(string eventName, function callback) => this

once(object events ) => this

-
// Attach the same callback to `event1` & `event2`. `event1` callback may be executed a single time, as `event2`.
+
// Attach the same callback to `event1` & `event2`. `event1` callback may be
+// executed a single time, as `event2`.
 eventListener.once( 'event1 event2', () => Promise.resolve( 'foo' ));
-// Bind a callback that returns 'foo' on `event1`, and 'bar' on `event2`. Both will be run a single time.
+// Bind a callback that returns 'foo' on `event1`, and 'bar' on `event2`. Both
+// will be run a single time.
 eventListener.once({
     event1: () => Promise.resolve( 'foo' ),
     event2: () => Promise.resolve( 'bar' ),
@@ -327,7 +335,7 @@ 
 
 	Documentation generated by JSDoc 3.5.5
 	
-		on 2017-10-30T19:51:10+01:00
+		on 2017-10-30T23:02:18+01:00
 	
 	using the DocStrap template.
 
diff --git a/docs/quicksearch.html b/docs/quicksearch.html
index 58338ee..4c9db39 100644
--- a/docs/quicksearch.html
+++ b/docs/quicksearch.html
@@ -7,7 +7,7 @@