Migrate to TypeScript and use Map (#99)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Migrate to TypeScript & Microbundle, move to Map for event handler storage
authored by Jack Franklin · committed by GitHub · parent cfd246c · Browse files · 8 files·+152 added−221 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+152 added−221 removed
- tests:+35 added−28 removed
- other:+117 added−193 removed
Provenance
- Commit
be5237f- Tree
c5cae9f- Author
Jack Franklin <jack@jackfranklin.net>- Committer
GitHub <noreply@github.com>- Parent
cfd246c
8 files changed+152 added−221 removed
deleted:src/index.js-63 removed
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263// @flow// An event handler can take an optional event argument// and should not return a valuetype EventHandler = (event?: any) => void;type WildCardEventHandler = (type: string, event?: any) => void
// An array of all currently registered event handlers for a typetype EventHandlerList = Array<EventHandler>;type WildCardEventHandlerList = Array<WildCardEventHandler>;// A map of event types and their corresponding event handlers.type EventHandlerMap = { '*'?: WildCardEventHandlerList, [type: string]: EventHandlerList,};
/** Mitt: Tiny (~200b) functional event emitter / pubsub. * @name mitt * @returns {Mitt} */export default function mitt(all: EventHandlerMap) { all = all || Object.create(null);
return { /** * Register an event handler for the given type. * * @param {String} type Type of event to listen for, or `"*"` for all events * @param {Function} handler Function to call in response to given event * @memberOf mitt */ on(type: string, handler: EventHandler) { (all[type] || (all[type] = [])).push(handler); },
/** * Remove an event handler for the given type. * * @param {String} type Type of event to unregister `handler` from, or `"*"` * @param {Function} handler Handler function to remove * @memberOf mitt */ off(type: string, handler: EventHandler) { if (all[type]) { all[type].splice(all[type].indexOf(handler) >>> 0, 1); } },
/** * Invoke all handlers for the given type. * If present, `"*"` handlers are invoked after type-matched handlers. * * Note: Manually firing "*" handlers is not supported. * * @param {String} type The event type to invoke * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler * @memberOf mitt */ emit(type: string, evt: any) { (all[type] || []).slice().map((handler) => { handler(evt); }); (all['*'] || []).slice().map((handler) => { handler(type, evt); }); } };}added:src/index.ts+75 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475type EventType = string | symbol;
// An event handler can take an optional event argument// and should not return a valuetype Handler = (event?: any) => void;type WildcardHandler= (type: EventType, event?: any) => void
// An array of all currently registered event handlers for a typetype EventHandlerList = Array<Handler>;type WildCardEventHandlerList = Array<WildcardHandler>;
// A map of event types and their corresponding event handlers.type EventHandlerMap = Map<EventType, EventHandlerList | WildCardEventHandlerList>;
export interface Emitter { on(type: EventType, handler: Handler): void; on(type: "*", handler: WildcardHandler): void;
off(type: EventType, handler: Handler): void; off(type: "*", handler: WildcardHandler): void;
emit<T = any>(type: EventType, event?: T): void; emit(type: "*", event?: any): void;}
/** Mitt: Tiny (~200b) functional event emitter / pubsub. * @name mitt * @returns {Mitt} */export default function mitt(all: EventHandlerMap): Emitter { all = all || new Map();
return { /** * Register an event handler for the given type. * * @param {string|symbol} type Type of event to listen for, or `"*"` for all events * @param {Function} handler Function to call in response to given event * @memberOf mitt */ on(type: EventType, handler: Handler) { const handlers = (all.get(type) || []); handlers.push(handler); all.set(type, handlers); },
/** * Remove an event handler for the given type. * * @param {string|symbol} type Type of event to unregister `handler` from, or `"*"` * @param {Function} handler Handler function to remove * @memberOf mitt */ off(type: EventType, handler: Handler) { if (all.has(type)) { all.get(type).splice(all.get(type).indexOf(handler) >>> 0, 1); } },
/** * Invoke all handlers for the given type. * If present, `"*"` handlers are invoked after type-matched handlers. * * Note: Manually firing "*" handlers is not supported. * * @param {string|symbol} type The event type to invoke * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler * @memberOf mitt */ emit(type: EventType, evt: any) { ((all.get(type) || []) as EventHandlerList).slice().map((handler) => { handler(evt); }); ((all.get('*') || []) as WildCardEventHandlerList).slice().map((handler) => { handler(type, evt); }); } };}modified:test/index.js+35 added-28 removed
10 unmodified lines11 describe('mitt#', () => {12 let events, inst;13 14 beforeEach( () => {15- events = Object.create(null);15+ events = new Map();16 inst = mitt(events);17 });18 19 describe('on()', () => {3 unmodified lines23 .that.is.a('function');24 });25 26 it('should register handler for new type', () => {27- let foo = () => {};27+ const foo = () => {};28 inst.on('foo', foo);29 30- expect(events).to.have.property('foo').that.deep.equals([foo]);30+ expect(events.get('foo')).to.deep.equal([foo]);31 });32 33 it('should register handlers for any type strings', () => {34- let foo = () => {};34+ const foo = () => {};35 inst.on('constructor', foo);36 37- expect(events).to.have.property('constructor').that.deep.equals([foo]);37+ expect(events.get('constructor')).to.deep.equal([foo]);38 });39 40 it('should append handler for existing type', () => {41- let foo = () => {};42- let bar = () => {};41+ const foo = () => {};42+ const bar = () => {};43 inst.on('foo', foo);44 inst.on('foo', bar);45 46- expect(events).to.have.property('foo').that.deep.equals([foo, bar]);46+ expect(events.get('foo')).to.deep.equal([foo, bar]);47 });48 49 it('should NOT normalize case', () => {50- let foo = () => {};50+ const foo = () => {};51 inst.on('FOO', foo);52 inst.on('Bar', foo);53 inst.on('baz:baT!', foo);54 55- expect(events).to.have.property('FOO').that.deep.equals([foo]);56- expect(events).to.not.have.property('foo');57- expect(events).to.have.property('Bar').that.deep.equals([foo]);58- expect(events).to.not.have.property('bar');59- expect(events).to.have.property('baz:baT!').that.deep.equals([foo]);55+ expect(events.get('FOO')).to.deep.equal([foo]);56+ expect(events.has('foo')).to.equal(false);57+ expect(events.get('Bar')).to.deep.equal([foo]);58+ expect(events.has('bar')).to.equal(false);59+ expect(events.get('baz:baT!')).to.deep.equal([foo]);60 });61+62+ it('can take symbols for event types', () => {63+ const foo = () => {};64+ const eventType = Symbol('eventType');65+ inst.on(eventType, foo);66+ expect(events.get(eventType)).to.deep.equal([foo]);67+ });68 });69 70 describe('off()', () => {71 it('should be a function', () => {2 unmodified lines74 .that.is.a('function');75 });76 77 it('should remove handler for type', () => {71- let foo = () => {};78+ const foo = () => {};79 inst.on('foo', foo);80 inst.off('foo', foo);81 75- expect(events).to.have.property('foo').that.is.empty;82+ expect(events.get('foo')).to.be.empty;83 });84 85 it('should NOT normalize case', () => {79- let foo = () => {};86+ const foo = () => {};87 inst.on('FOO', foo);88 inst.on('Bar', foo);89 inst.on('baz:bat!', foo);90 91 inst.off('FOO', foo);92 inst.off('Bar', foo);93 inst.off('baz:baT!', foo);94 88- expect(events).to.have.property('FOO').that.is.empty;89- expect(events).to.not.have.property('foo');90- expect(events).to.have.property('Bar').that.is.empty;91- expect(events).to.not.have.property('bar');92- expect(events).to.have.property('baz:bat!').with.length(1);95+ expect(events.get('FOO')).to.be.empty;96+ expect(events.has('foo')).to.equal(false);97+ expect(events.get('Bar')).to.be.empty;98+ expect(events.has('bar')).to.equal(false);99+ expect(events.get('baz:bat!')).to.have.lengthOf(1);100 });101 });102 103 describe('emit()', () => {3 unmodified lines107 .that.is.a('function');108 });109 110 it('should invoke handler for type', () => {104- let event = { a: 'b' };111+ const event = { a: 'b' };112 113 inst.on('foo', (one, two) => {114 expect(one).to.deep.equal(event);115 expect(two).to.be.an('undefined');2 unmodified lines118 inst.emit('foo', event);119 });120 121 it('should NOT ignore case', () => {115- let onFoo = spy(),122+ const onFoo = spy(),123 onFOO = spy();117- events.Foo = [onFoo];118- events.FOO = [onFOO];124+ events.set('Foo', [onFoo]);125+ events.set('FOO', [onFOO]);126 127 inst.emit('Foo', 'Foo arg');128 inst.emit('FOO', 'FOO arg');129 1 unmodified line131 expect(onFOO).to.have.been.calledOnce.and.calledWith('FOO arg');132 });133 134 it('should invoke * handlers', () => {128- let star = spy(),135+ const star = spy(),136 ea = { a: 'a' },137 eb = { b: 'b' };138 132- events['*'] = [star];139+ events.set('*', [star]);140 141 inst.emit('foo', ea);142 expect(star).to.have.been.calledOnce.and.calledWith('foo', ea);143 star.reset();6 unmodified linesdeleted:mitt.d.ts-53 removed
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253declare var mitt: mitt.MittStatic;
declare module "mitt" { export = mitt;}
declare namespace mitt { type Handler = (event?: any) => void; type WildcardHandler = (type: string, event?: any) => void;
interface MittStatic { (all?: {[key: string]: Array<Handler>}): Emitter; }
interface Emitter { /** * Register an event handler for the given type. * * @param {string} type Type of event to listen for, or `"*"` for all events. * @param {Handler} handler Function to call in response to the given event. * * @memberOf Mitt */ on(type: string, handler: Handler): void; on(type: "*", handler: WildcardHandler): void;
/** * Function to call in response to the given event * * @param {string} type Type of event to unregister `handler` from, or `"*"` * @param {Handler} handler Handler function to remove. * * @memberOf Mitt */ off(type: string, handler: Handler): void; off(type: "*", handler: WildcardHandler): void;
/** * Invoke all handlers for the given type. * If present, `"*"` handlers are invoked prior to type-matched handlers. * * @param {string} type The event type to invoke * @param {any} [event] An event object, passed to each handler * * @memberOf Mitt */ emit(type: string, event?: any): void; /** * Note: Manually firing "*" events is unsupported. */ emit(type: "*", event?: any): void; }}modified:package.json+25 added-35 removed
123456789101112111213141314151617181617181919202122238 unmodified lines3233343536373637394041424344454647384950394041424344454647487 unmodified lines565758596660616263646569667172737475676869777071728081737475767778878889798081829483848586{ "name": "mitt", "version": "1.2.0", "description": "Tiny 200b functional Event Emitter / pubsub.", "jsnext:main": "dist/mitt.es.js", "source": "src/index.ts", "module": "dist/mitt.es.js", "main": "dist/mitt.js", "umd:main": "dist/mitt.umd.js", "typings": "dist/index.d.ts", "scripts": { "bump": "standard-version", "testonly": "mocha --require esm --require flow-remove-types/register test/**/*.js", "lint": "eslint src test", "test": "flow && npm run lint && npm run testonly", "build": "npm-run-all --silent clean -p rollup -p minify:* -s docs size", "testonly": "mocha --require esm --require ts-node/register test/**/*.js", "lint": "eslint src test --ext ts --ext js", "test": "tsc src/index.ts --noEmit && npm run lint && npm run testonly", "bundle": "microbundle", "build": "npm-run-all --silent clean -p bundle -s docs size", "clean": "rimraf dist", "rollup": "rollup -c", "minify:cjs": "uglifyjs $npm_package_main -cm toplevel -o $npm_package_main -p relative --in-source-map ${npm_package_main}.map --source-map ${npm_package_main}.map", "minify:umd": "uglifyjs $npm_package_umd_main -cm -o $npm_package_umd_main -p relative --in-source-map ${npm_package_umd_main}.map --source-map ${npm_package_umd_main}.map", "docs": "documentation readme src/index.js --section API -q", "docs": "documentation readme src/index.ts --section API -q --parse-extension ts", "size": "echo \"Gzipped Size: $(strip-json-comments --no-whitespace $npm_package_main | gzip-size | pretty-bytes)\"", "release": "npm run build -s && npm run bump && git push --follow-tags origin master && npm publish" }, "repository": "developit/mitt",8 unmodified lines ], "license": "MIT", "files": [ "src", "dist", "mitt.d.ts" "dist" ], "babel": { "presets": [ "es2015", "stage-0" ], "plugins": [ "transform-flow-strip-types" ] }, "eslintConfig": { "extends": "eslint:recommended", "parser": "babel-eslint", "extends": [ "eslint:recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended" ], "parser": "@typescript-eslint/parser", "parserOptions": { "sourceType": "module" }, "env": {7 unmodified lines "rules": { "semi": [ 2, "always" ] ], "@typescript-eslint/no-explicit-any": 0, "@typescript-eslint/explicit-function-return-type": 0, "@typescript-eslint/no-empty-function": 0 } }, "typings": "./mitt.d.ts", "devDependencies": { "babel-core": "^6.9.1", "babel-eslint": "^10.0.3", "babel-plugin-transform-flow-strip-types": "^6.21.0", "babel-preset-es2015": "^6.9.0", "babel-preset-stage-0": "^6.5.0", "@typescript-eslint/eslint-plugin": "^2.34.0", "@typescript-eslint/parser": "^2.34.0", "chai": "^3.5.0", "documentation": "^4.0.0-beta4", "documentation": "^13.0.0", "eslint": "^6.5.1", "esm": "^3.2.25", "flow-bin": "^0.38.0", "flow-remove-types": "^1.2.0", "gzip-size-cli": "^1.0.0", "microbundle": "^0.12.0", "mocha": "^3.2.0", "npm-run-all": "^2.1.1", "pretty-bytes-cli": "^2.0.0", "rimraf": "^2.5.2", "rollup": "^0.41.4", "rollup-plugin-buble": "^0.15.0", "rollup-plugin-flow": "^1.1.1", "sinon": "^1.17.4", "sinon-chai": "^2.8.0", "standard-version": "^4.0.0", "strip-json-comments-cli": "^1.0.1", "uglify-js": "^2.6.2" "ts-node": "^8.10.1", "typescript": "^3.9.3" }}modified:README.md+17 added-17 removed
93 unmodified lines94 ## API95 96 <!-- Generated by documentation.js. Update this documentation by updating the source code. -->97 98+#### Table of Contents99+100+- [mitt](#mitt)101+- [on](#on)102+ - [Parameters](#parameters)103+- [off](#off)104+ - [Parameters](#parameters-1)105+- [emit](#emit)106+ - [Parameters](#parameters-2)107+108 ### mitt109 110 Mitt: Tiny (~200b) functional event emitter / pubsub.111 102-**Parameters**103-104-- `all` **EventHandlerMap** 105-112 Returns **Mitt** 113 114 ### on115 116 Register an event handler for the given type.117 112-**Parameters**118+#### Parameters119 114-- `type` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Type of event to listen for, or `"*"` for all events120+- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to listen for, or `"*"` for all events121 - `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** Function to call in response to given event122 123 ### off124 125 Remove an event handler for the given type.126 121-**Parameters**127+#### Parameters128 123-- `type` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Type of event to unregister `handler` from, or `"*"`129+- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to unregister `handler` from, or `"*"`130 - `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** Handler function to remove131 132 ### emit133 134 Invoke all handlers for the given type.135 If present, `"*"` handlers are invoked after type-matched handlers.136 131-_Note: Manually firing "*" handlers is not supported._137+Note: Manually firing "\*" handlers is not supported.138 133-**Parameters**139+#### Parameters140 135-- `type` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The event type to invoke141+- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** The event type to invoke142 - `evt` **Any?** Any value (object is recommended and powerful), passed to each handler143 144 ## Contribute145 146 First off, thanks for taking the time to contribute!147 Now, take a moment to be sure your contributions make sense to everyone else.148 143-Development Start:144-145-This project is typed with Flow Type annotations. To ensure you have the proper typings for this project run146-147-`flow-typed install`148-149 ### Reporting Issues150 151 Found a problem? Want a new feature? First of all see if your issue or idea has [already been reported](../../issues).152 If don't, just open a [new clear and descriptive issue](../../issues/new).18 unmodified linesdeleted:rollup.config.js-20 removed
1234567891011121314151617181920import buble from 'rollup-plugin-buble';import flow from 'rollup-plugin-flow';import fs from 'fs';
const pkg = JSON.parse(fs.readFileSync('./package.json'));
export default { entry: 'src/index.js', useStrict: false, sourceMap: true, plugins: [ flow(), buble() ], targets: [ { dest: pkg.main, format: 'cjs' }, { dest: pkg.module, format: 'es' }, { dest: pkg['umd:main'], format: 'umd', moduleName: pkg.name } ]};deleted:typings.json-5 removed
1-{2- "name": "mitt",3- "main": "mitt.d.ts",4- "version": false5-}