Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

readme.md 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. # <img src="media/header.png" width="1000">
  2. > Simple and modern async event emitter
  3. [![Coverage Status](https://codecov.io/gh/sindresorhus/emittery/branch/master/graph/badge.svg)](https://codecov.io/gh/sindresorhus/emittery)
  4. [![](https://badgen.net/bundlephobia/minzip/emittery)](https://bundlephobia.com/result?p=emittery)
  5. It works in Node.js and the browser (using a bundler).
  6. Emitting events asynchronously is important for production code where you want the least amount of synchronous operations. Since JavaScript is single-threaded, no other code can run while doing synchronous operations. For Node.js, that means it will block other requests, defeating the strength of the platform, which is scalability through async. In the browser, a synchronous operation could potentially cause lags and block user interaction.
  7. ## Install
  8. ```
  9. $ npm install emittery
  10. ```
  11. ## Usage
  12. ```js
  13. const Emittery = require('emittery');
  14. const emitter = new Emittery();
  15. emitter.on('🦄', data => {
  16. console.log(data);
  17. });
  18. const myUnicorn = Symbol('🦄');
  19. emitter.on(myUnicorn, data => {
  20. console.log(`Unicorns love ${data}`);
  21. });
  22. emitter.emit('🦄', '🌈'); // Will trigger printing '🌈'
  23. emitter.emit(myUnicorn, '🦋'); // Will trigger printing 'Unicorns love 🦋'
  24. ```
  25. ## API
  26. ### eventName
  27. Emittery accepts strings and symbols as event names.
  28. Symbol event names can be used to avoid name collisions when your classes are extended, especially for internal events.
  29. ### emitter = new Emittery()
  30. #### on(eventName | eventName[], listener)
  31. Subscribe to one or more events.
  32. Returns an unsubscribe method.
  33. Using the same listener multiple times for the same event will result in only one method call per emitted event.
  34. ```js
  35. const Emittery = require('emittery');
  36. const emitter = new Emittery();
  37. emitter.on('🦄', data => {
  38. console.log(data);
  39. });
  40. emitter.on(['🦄', '🐶'], data => {
  41. console.log(data);
  42. });
  43. emitter.emit('🦄', '🌈'); // log => '🌈' x2
  44. emitter.emit('🐶', '🍖'); // log => '🍖'
  45. ```
  46. ##### Custom subscribable events
  47. Emittery exports some symbols which represent custom events that can be passed to `Emitter.on` and similar methods.
  48. - `Emittery.listenerAdded` - Fires when an event listener was added.
  49. - `Emittery.listenerRemoved` - Fires when an event listener was removed.
  50. ```js
  51. const Emittery = require('emittery');
  52. const emitter = new Emittery();
  53. emitter.on(Emittery.listenerAdded, ({listener, eventName}) => {
  54. console.log(listener);
  55. //=> data => {}
  56. console.log(eventName);
  57. //=> '🦄'
  58. });
  59. emitter.on('🦄', data => {
  60. // Handle data
  61. });
  62. ```
  63. ###### Listener data
  64. - `listener` - The listener that was added.
  65. - `eventName` - The name of the event that was added or removed if `.on()` or `.off()` was used, or `undefined` if `.onAny()` or `.offAny()` was used.
  66. Only events that are not of this type are able to trigger these events.
  67. ##### listener(data)
  68. #### off(eventName | eventName[], listener)
  69. Remove one or more event subscriptions.
  70. ```js
  71. const Emittery = require('emittery');
  72. const emitter = new Emittery();
  73. const listener = data => console.log(data);
  74. (async () => {
  75. emitter.on(['🦄', '🐶', '🦊'], listener);
  76. await emitter.emit('🦄', 'a');
  77. await emitter.emit('🐶', 'b');
  78. await emitter.emit('🦊', 'c');
  79. emitter.off('🦄', listener);
  80. emitter.off(['🐶', '🦊'], listener);
  81. await emitter.emit('🦄', 'a'); // Nothing happens
  82. await emitter.emit('🐶', 'b'); // Nothing happens
  83. await emitter.emit('🦊', 'c'); // Nothing happens
  84. })();
  85. ```
  86. ##### listener(data)
  87. #### once(eventName | eventName[])
  88. Subscribe to one or more events only once. It will be unsubscribed after the first event.
  89. Returns a promise for the event data when `eventName` is emitted.
  90. ```js
  91. const Emittery = require('emittery');
  92. const emitter = new Emittery();
  93. emitter.once('🦄').then(data => {
  94. console.log(data);
  95. //=> '🌈'
  96. });
  97. emitter.once(['🦄', '🐶']).then(data => {
  98. console.log(data);
  99. });
  100. emitter.emit('🦄', '🌈'); // Log => '🌈' x2
  101. emitter.emit('🐶', '🍖'); // Nothing happens
  102. ```
  103. #### events(eventName)
  104. Get an async iterator which buffers data each time an event is emitted.
  105. Call `return()` on the iterator to remove the subscription.
  106. ```js
  107. const Emittery = require('emittery');
  108. const emitter = new Emittery();
  109. const iterator = emitter.events('🦄');
  110. emitter.emit('🦄', '🌈1'); // Buffered
  111. emitter.emit('🦄', '🌈2'); // Buffered
  112. iterator
  113. .next()
  114. .then(({value, done}) => {
  115. // done === false
  116. // value === '🌈1'
  117. return iterator.next();
  118. })
  119. .then(({value, done}) => {
  120. // done === false
  121. // value === '🌈2'
  122. // Revoke subscription
  123. return iterator.return();
  124. })
  125. .then(({done}) => {
  126. // done === true
  127. });
  128. ```
  129. In practice, you would usually consume the events using the [for await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) statement. In that case, to revoke the subscription simply break the loop.
  130. ```js
  131. const Emittery = require('emittery');
  132. const emitter = new Emittery();
  133. const iterator = emitter.events('🦄');
  134. emitter.emit('🦄', '🌈1'); // Buffered
  135. emitter.emit('🦄', '🌈2'); // Buffered
  136. // In an async context.
  137. for await (const data of iterator) {
  138. if (data === '🌈2') {
  139. break; // Revoke the subscription when we see the value '🌈2'.
  140. }
  141. }
  142. ```
  143. It accepts multiple event names.
  144. ```js
  145. const Emittery = require('emittery');
  146. const emitter = new Emittery();
  147. const iterator = emitter.events(['🦄', '🦊']);
  148. emitter.emit('🦄', '🌈1'); // Buffered
  149. emitter.emit('🦊', '🌈2'); // Buffered
  150. iterator
  151. .next()
  152. .then(({value, done}) => {
  153. // done === false
  154. // value === '🌈1'
  155. return iterator.next();
  156. })
  157. .then(({value, done}) => {
  158. // done === false
  159. // value === '🌈2'
  160. // Revoke subscription
  161. return iterator.return();
  162. })
  163. .then(({done}) => {
  164. // done === true
  165. });
  166. ```
  167. #### emit(eventName, data?)
  168. Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but executed concurrently.
  169. Returns a promise that resolves when all the event listeners are done. *Done* meaning executed if synchronous or resolved when an async/promise-returning function. You usually wouldn't want to wait for this, but you could for example catch possible errors. If any of the listeners throw/reject, the returned promise will be rejected with the error, but the other listeners will not be affected.
  170. #### emitSerial(eventName, data?)
  171. Same as above, but it waits for each listener to resolve before triggering the next one. This can be useful if your events depend on each other. Although ideally they should not. Prefer `emit()` whenever possible.
  172. If any of the listeners throw/reject, the returned promise will be rejected with the error and the remaining listeners will *not* be called.
  173. #### onAny(listener)
  174. Subscribe to be notified about any event.
  175. Returns a method to unsubscribe.
  176. ##### listener(eventName, data)
  177. #### offAny(listener)
  178. Remove an `onAny` subscription.
  179. #### anyEvent()
  180. Get an async iterator which buffers a tuple of an event name and data each time an event is emitted.
  181. Call `return()` on the iterator to remove the subscription.
  182. ```js
  183. const Emittery = require('emittery');
  184. const emitter = new Emittery();
  185. const iterator = emitter.anyEvent();
  186. emitter.emit('🦄', '🌈1'); // Buffered
  187. emitter.emit('🌟', '🌈2'); // Buffered
  188. iterator.next()
  189. .then(({value, done}) => {
  190. // done === false
  191. // value is ['🦄', '🌈1']
  192. return iterator.next();
  193. })
  194. .then(({value, done}) => {
  195. // done === false
  196. // value is ['🌟', '🌈2']
  197. // Revoke subscription
  198. return iterator.return();
  199. })
  200. .then(({done}) => {
  201. // done === true
  202. });
  203. ```
  204. In the same way as for `events`, you can subscribe by using the `for await` statement
  205. #### clearListeners(eventNames?)
  206. Clear all event listeners on the instance.
  207. If `eventNames` is given, only the listeners for that events are cleared.
  208. #### listenerCount(eventNames?)
  209. The number of listeners for the `eventNames` or all events if not specified.
  210. #### bindMethods(target, methodNames?)
  211. Bind the given `methodNames`, or all `Emittery` methods if `methodNames` is not defined, into the `target` object.
  212. ```js
  213. import Emittery = require('emittery');
  214. const object = {};
  215. new Emittery().bindMethods(object);
  216. object.emit('event');
  217. ```
  218. ## TypeScript
  219. The default `Emittery` class has generic types that can be provided by TypeScript users to strongly type the list of events and the data passed to their event listeners.
  220. ```ts
  221. import Emittery = require('emittery');
  222. const emitter = new Emittery<
  223. // Pass `{[eventName]: undefined | <eventArg>}` as the first type argument for events that pass data to their listeners.
  224. // A value of `undefined` in this map means the event listeners should expect no data, and a type other than `undefined` means the listeners will receive one argument of that type.
  225. {
  226. open: string,
  227. close: undefined
  228. }
  229. >();
  230. // Typechecks just fine because the data type for the `open` event is `string`.
  231. emitter.emit('open', 'foo\n');
  232. // Typechecks just fine because `close` is present but points to undefined in the event data type map.
  233. emitter.emit('close');
  234. // TS compilation error because `1` isn't assignable to `string`.
  235. emitter.emit('open', 1);
  236. // TS compilation error because `other` isn't defined in the event data type map.
  237. emitter.emit('other');
  238. ```
  239. ### Emittery.mixin(emitteryPropertyName, methodNames?)
  240. A decorator which mixins `Emittery` as property `emitteryPropertyName` and `methodNames`, or all `Emittery` methods if `methodNames` is not defined, into the target class.
  241. ```ts
  242. import Emittery = require('emittery');
  243. @Emittery.mixin('emittery')
  244. class MyClass {}
  245. const instance = new MyClass();
  246. instance.emit('event');
  247. ```
  248. ## Scheduling details
  249. Listeners are not invoked for events emitted *before* the listener was added. Removing a listener will prevent that listener from being invoked, even if events are in the process of being (asynchronously!) emitted. This also applies to `.clearListeners()`, which removes all listeners. Listeners will be called in the order they were added. So-called *any* listeners are called *after* event-specific listeners.
  250. Note that when using `.emitSerial()`, a slow listener will delay invocation of subsequent listeners. It's possible for newer events to overtake older ones.
  251. ## FAQ
  252. ### How is this different than the built-in `EventEmitter` in Node.js?
  253. There are many things to not like about `EventEmitter`: its huge API surface, synchronous event emitting, magic error event, flawed memory leak detection. Emittery has none of that.
  254. ### Isn't `EventEmitter` synchronous for a reason?
  255. Mostly backwards compatibility reasons. The Node.js team can't break the whole ecosystem.
  256. It also allows silly code like this:
  257. ```js
  258. let unicorn = false;
  259. emitter.on('🦄', () => {
  260. unicorn = true;
  261. });
  262. emitter.emit('🦄');
  263. console.log(unicorn);
  264. //=> true
  265. ```
  266. But I would argue doing that shows a deeper lack of Node.js and async comprehension and is not something we should optimize for. The benefit of async emitting is much greater.
  267. ### Can you support multiple arguments for `emit()`?
  268. No, just use [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment):
  269. ```js
  270. emitter.on('🦄', ([foo, bar]) => {
  271. console.log(foo, bar);
  272. });
  273. emitter.emit('🦄', [foo, bar]);
  274. ```
  275. ## Related
  276. - [p-event](https://github.com/sindresorhus/p-event) - Promisify an event by waiting for it to be emitted