index.js
This file
Path
src/index.js
59 lines · 1.8 KiB · JavaScript
Last changed by
refactor: fixes #2, #6, #12 and #13tunnckoCorebefore adoptiona6190e9
History of this fileTake it
1/** Mitt: Tiny (~200b) functional event emitter / pubsub.refactor: fixes #2, #6, #12 and #13tunnckoCorebefore adoptiona6190e9
lines 2–3why, one step back2 * @name mitt3 * @returns {Mitt}4 */refactor: fixes #2, #6, #12 and #13tunnckoCorebefore adoptiona6190e9
lines 5–7why, one step back5export default function mitt () {6 let ret = {7 all: Object.create(null),8refactor: fixes #2, #6, #12 and #13tunnckoCorebefore adoptiona6190e9
lines 9–20why, one step back9 /**10 * Register an event handler for the given type.11 *12 * @param {String} type Type of event to listen for, or `"*"` for all events13 * @param {Function} handler Function to call in response to given event14 * @return {Object} the `mitt` instance for chaining15 * @memberOf mitt16 */17 on(type, handler) {18 list(type).add(handler);19 return ret;20 },21refactor: fixes #2, #6, #12 and #13tunnckoCorebefore adoptiona6190e9
lines 22–33why, one step back22 /**23 * Remove an event handler for the given type.24 *25 * @param {String} type Type of event to unregister `handler` from, or `"*"`26 * @param {Function} handler Handler function to remove27 * @return {Object} the `mitt` instance for chaining28 * @memberOf mitt29 */30 off(type, handler) {31 list(type).delete(handler);32 return ret;33 },34refactor: fixes #2, #6, #12 and #13tunnckoCorebefore adoptiona6190e9
lines 35–51why, one step back35 /**36 * Invoke all handlers for the given type.37 * If present, `"*"` handlers are invoked prior to type-matched handlers.38 *39 * @param {String} type The event type to invoke40 * @param {Any} [arg1] A value (first argument), passed to each handler41 * @param {Any} [arg2] A value (second argument), passed to each handler42 * @param {Any} [arg3] A value (third argument), passed to each handler43 * @return {Object} the `mitt` instance for chaining44 * @memberof mitt45 */46 emit(type, arg1, arg2, arg3) {47 list(type).forEach((handler) => handler(arg1, arg2, arg3));48 list('*').forEach((handler) => handler(type, arg1, arg2, arg3));49 return ret;50 }51 };52refactor: fixes #2, #6, #12 and #13tunnckoCorebefore adoptiona6190e9
lines 53–56why, one step back53 // Get or create a named handler list54 let list = (type) => {55 return ret.all[type = type.toLowerCase()] || (ret.all[type] = new Set());56 };57refactor: fixes #2, #6, #12 and #13tunnckoCorebefore adoptiona6190e9
line 58why, one step back58 return ret;59}