UNPKG

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