1 | [](https://travis-ci.org/DirtyHairy/microevent)
|
2 | [](https://badge.fury.io/js/microevent.ts)
|
3 |
|
4 | # What is it?
|
5 |
|
6 | This package implements an event system with minimal dispatch overhead. Instead
|
7 | of recording handlers bound to an event in dynamic data structures, this library
|
8 | binds the handlers to autogenerated code. This enables the VM to inline the
|
9 | handler invocation and generate code that is just as fast as invoking the handlers
|
10 | directly.
|
11 |
|
12 | In a (completely unscientific) benchmark, this library performs bettern than
|
13 | NodeJS events in terms of event dispatch calls per second by about two orders
|
14 | of magnitude.
|
15 |
|
16 | # How to use it?
|
17 |
|
18 | ## Installation
|
19 |
|
20 | You can install the library into your project via npm
|
21 |
|
22 | npm install microevent.ts
|
23 |
|
24 | The library is written in Typescript and will work in any environment that
|
25 | supports ES5. No external typings are required for using this library with
|
26 | Typescript (version >= 2).
|
27 |
|
28 | ## Importing
|
29 |
|
30 | ES5 / CommonJS
|
31 |
|
32 | var Event = require('microevent.ts').Event;
|
33 |
|
34 | ES6
|
35 |
|
36 | import {Event} from 'microevent.ts';
|
37 |
|
38 | Typescript
|
39 |
|
40 | import {Event, EventInterface} from 'microevent.ts';
|
41 |
|
42 | The `EventInterface` covers only the client side of an event, that is adding
|
43 | and removing handlers.
|
44 |
|
45 | ## API
|
46 |
|
47 | ### Creating
|
48 |
|
49 | ES5/ES6
|
50 |
|
51 | const event = new Event();
|
52 |
|
53 | Typescript
|
54 |
|
55 | const event = new Event<PayloadT>();
|
56 |
|
57 | Create a new event that will dispatch a payload of type `PayloadT`.
|
58 |
|
59 | ### Dispatching
|
60 |
|
61 | event.dispatch(payload);
|
62 |
|
63 | This will call all handlers in the order they were registered, passing `payload`
|
64 | as first argument.
|
65 |
|
66 | **IMPORTANT** `dispatch` is a property that refers to dynamically generated code.
|
67 | **DO NOT KEEP ANY REFERENCES** to `dispatch` as adding and removing handlers
|
68 | will invalidate them.
|
69 |
|
70 | ### Registering handlers
|
71 |
|
72 | event.addHandler(handler, context);
|
73 |
|
74 | `context` is an optional parameter that will be passed to the handler on
|
75 | each invocation.
|
76 |
|
77 | ### Removing handlers
|
78 |
|
79 | event.removeHandler(handler, context);
|
80 |
|
81 | Both `handler` and `context` must be identical to the values used when registering
|
82 | the handler in the first place.
|
83 |
|
84 | ### Checking for handlers
|
85 |
|
86 | event.isHandlerAttached(handler, context)
|
87 |
|
88 | This will check whether a handler was attached in a given context.
|
89 |
|
90 | event.hasHandlers
|
91 |
|
92 | `true` if the event has any handlers attached, false otherwise.
|
93 |
|
94 | # License
|
95 |
|
96 | Feel free to use this library under the conditions of the MIT license.
|