index.js
This file
Path
src/index.js
47 lines · 1.3 KiB · JavaScript
Last changed by
Fixes #9: use Object.create(null) over {}Alexander Gudulinbefore adoption3fb2dc2
History of this fileTake it
1/** Mitt: Tiny (~200b) functional event emitter / pubsub.2 * @name mitt3 * @returns {Mitt}4 */5export default function mitt(all) {6 // Arrays of event handlers, keyed by typeFixes #9: use Object.create(null) over {}Alexander Gudulinbefore adoption3fb2dc2
line 7why, one step back7 all = all || Object.create(null);Initial commit! 🚀Jason Millerbefore adoptione77a42c
lines 8–4789 // Get or create a named handler list10 function list(type) {11 let t = type.toLowerCase();12 return all[t] || (all[t] = []);13 }1415 return {1617 /** Register an event handler for the given type.18 * @param {String} type Type of event to listen for, or `"*"` for all events19 * @param {Function} handler Function to call in response to the given event20 * @memberof mitt21 */22 on(type, handler) {23 list(type).push(handler);24 },2526 /** Remove an event handler for the given type.27 * @param {String} type Type of event to unregister `handler` from, or `"*"`28 * @param {Function} handler Handler function to remove29 * @memberof mitt30 */31 off(type, handler) {32 let e = list(type),33 i = e.indexOf(handler);34 if (~i) e.splice(i, 1);35 },3637 /** Invoke all handlers for the given type.38 * If present, `"*"` handlers are invoked prior to type-matched handlers.39 * @param {String} type The event type to invoke40 * @param {Any} [event] An event object, passed to each handler41 * @memberof mitt42 */43 emit(type, event) {44 list('*').concat(list(type)).forEach( f => { f(event); });45 }46 };47}