micro-typed-events
;;events.emit42;events.emit57;unsubscribe; events.emit99; // not loggedevents.emit'hey'; // not compiling
The smallest, most convenient, typesafe (with TS, but also works with normal JS), event emitter / pubsub system you'll ever need.
Unlike other event emitters, it does not use on/off/once
methods but only a single subscribe method and returns an unsubscribe handle, which makes it more tiny, easier to type, more convenient to use with arrow functions.
The most minimal code you need for a typesafe pub/sub system, and feature complete, making suitable to include as a dependency on other libraries.
Install
npm install --save micro-typed-events// oryarn add micro-typed-events
Usage
Simple typed events
; ; ; events.emit42;events.emit'hey'; // Does not compile unsubscribe;
Object typed events
; ;; ; events.emit;events.emit; // Does not compile unsubscribe;
Multiple-args typed events
; ; ; events.emit42, 'hello';events.emit'hello', 42; // Does not compile unsubscribe;
Advanced typing, dynamic args...
; // Listener type is any void function; ; ; events.emit'hey', 1, 'blaa', 'whatever', 'you', 'want', 1, 2, 3;events.emit1, 'hey', 'blaa', 'whatever', 'you', 'want', 1, 2, 3; // Does not compile unsubscribe;
Vanilla JS
; const events = ; const unsubscribe = events; events;events; // Does not fail, you should use typescript ;
FAQ
Should I create a single events object for all my events?
No, you should rather create one per event-type. You could expose all your events as an object, like this:
;
Can I unsubscribe directly inside a listener
Yes, listeners are able to unsubscribe themselves (or other listeners) without messing things up.
Can I subscribe directly inside a listener
Yes, but that listener will only be called on next emitted event.
Can I embed this library in my library?
Yes, this lib is very tiny. It exports ES and CJS modules. Here's the CJS output, I'll let you judge yourself if you can write something shorter:
'use strict'; Object; { var listeners = ; return { listeners; return { var index = listeners; if index > -1 listeners; }; } { var args = ; for var _i = 0; _i < argumentslength; _i++ args_i = arguments_i; // take care of user trying to unsub inside a listener listeners; } ;} exportscreateEvents = createEvents;//# sourceMappingURL=index.js.map
License
MIT © slorber
Hire a freelance expert
Looking for a React/ReactNative freelance expert with more than 5 years production experience? Contact me from my website or with Twitter.