• Stars
    star
    1,721
  • Rank 27,118 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple and modern async event emitter

Simple and modern async event emitter

It works in Node.js and the browser (using a bundler).

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.

Install

npm install emittery

Usage

import Emittery from 'emittery';

const emitter = new Emittery();

emitter.on('๐Ÿฆ„', data => {
	console.log(data);
});

const myUnicorn = Symbol('๐Ÿฆ„');

emitter.on(myUnicorn, data => {
	console.log(`Unicorns love ${data}`);
});

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ'); // Will trigger printing '๐ŸŒˆ'
emitter.emit(myUnicorn, '๐Ÿฆ‹');  // Will trigger printing 'Unicorns love ๐Ÿฆ‹'

API

eventName

Emittery accepts strings, symbols, and numbers as event names.

Symbol event names are preferred given that they can be used to avoid name collisions when your classes are extended, especially for internal events.

isDebugEnabled

Toggle debug mode for all instances.

Default: true if the DEBUG environment variable is set to emittery or *, otherwise false.

Example:

import Emittery from 'emittery';

Emittery.isDebugEnabled = true;

const emitter1 = new Emittery({debug: {name: 'myEmitter1'}});
const emitter2 = new Emittery({debug: {name: 'myEmitter2'}});

emitter1.on('test', data => {
	// โ€ฆ
});

emitter2.on('otherTest', data => {
	// โ€ฆ
});

emitter1.emit('test');
//=> [16:43:20.417][emittery:subscribe][myEmitter1] Event Name: test
//	data: undefined

emitter2.emit('otherTest');
//=> [16:43:20.417][emittery:subscribe][myEmitter2] Event Name: otherTest
//	data: undefined

emitter = new Emittery(options?)

Create a new instance of Emittery.

options?

Type: object

Configure the new instance of Emittery.

debug?

Type: object

Configure the debugging options for this instance.

name

Type: string
Default: undefined

Define a name for the instance of Emittery to use when outputting debug data.

Example:

import Emittery from 'emittery';

Emittery.isDebugEnabled = true;

const emitter = new Emittery({debug: {name: 'myEmitter'}});

emitter.on('test', data => {
	// โ€ฆ
});

emitter.emit('test');
//=> [16:43:20.417][emittery:subscribe][myEmitter] Event Name: test
//	data: undefined
enabled?

Type: boolean
Default: false

Toggle debug logging just for this instance.

Example:

import Emittery from 'emittery';

const emitter1 = new Emittery({debug: {name: 'emitter1', enabled: true}});
const emitter2 = new Emittery({debug: {name: 'emitter2'}});

emitter1.on('test', data => {
	// โ€ฆ
});

emitter2.on('test', data => {
	// โ€ฆ
});

emitter1.emit('test');
//=> [16:43:20.417][emittery:subscribe][emitter1] Event Name: test
//	data: undefined

emitter2.emit('test');
logger?

Type: Function(string, string, EventName?, Record<string, any>?) => void

Default:

(type, debugName, eventName, eventData) => {
	if (typeof eventData === 'object') {
		eventData = JSON.stringify(eventData);
	}

	if (typeof eventName === 'symbol' || typeof eventName === 'number') {
		eventName = eventName.toString();
	}

	const currentTime = new Date();
	const logTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}.${currentTime.getMilliseconds()}`;
	console.log(`[${logTime}][emittery:${type}][${debugName}] Event Name: ${eventName}\n\tdata: ${eventData}`);
}

Function that handles debug data.

Example:

import Emittery from 'emittery';

const myLogger = (type, debugName, eventName, eventData) => {
	console.log(`[${type}]: ${eventName}`);
};

const emitter = new Emittery({
	debug: {
		name: 'myEmitter',
		enabled: true,
		logger: myLogger
	}
});

emitter.on('test', data => {
	// โ€ฆ
});

emitter.emit('test');
//=> [subscribe]: test

on(eventName | eventName[], listener)

Subscribe to one or more events.

Returns an unsubscribe method.

Using the same listener multiple times for the same event will result in only one method call per emitted event.

import Emittery from 'emittery';

const emitter = new Emittery();

emitter.on('๐Ÿฆ„', data => {
	console.log(data);
});

emitter.on(['๐Ÿฆ„', '๐Ÿถ'], data => {
	console.log(data);
});

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ'); // log => '๐ŸŒˆ' x2
emitter.emit('๐Ÿถ', '๐Ÿ–'); // log => '๐Ÿ–'
Custom subscribable events

Emittery exports some symbols which represent "meta" events that can be passed to Emitter.on and similar methods.

  • Emittery.listenerAdded - Fires when an event listener was added.
  • Emittery.listenerRemoved - Fires when an event listener was removed.
import Emittery from 'emittery';

const emitter = new Emittery();

emitter.on(Emittery.listenerAdded, ({listener, eventName}) => {
	console.log(listener);
	//=> data => {}

	console.log(eventName);
	//=> '๐Ÿฆ„'
});

emitter.on('๐Ÿฆ„', data => {
	// Handle data
});
Listener data
  • listener - The listener that was added.
  • 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.

Only events that are not of this type are able to trigger these events.

listener(data)

off(eventName | eventName[], listener)

Remove one or more event subscriptions.

import Emittery from 'emittery';

const emitter = new Emittery();

const listener = data => {
	console.log(data);
};

emitter.on(['๐Ÿฆ„', '๐Ÿถ', '๐ŸฆŠ'], listener);
await emitter.emit('๐Ÿฆ„', 'a');
await emitter.emit('๐Ÿถ', 'b');
await emitter.emit('๐ŸฆŠ', 'c');
emitter.off('๐Ÿฆ„', listener);
emitter.off(['๐Ÿถ', '๐ŸฆŠ'], listener);
await emitter.emit('๐Ÿฆ„', 'a'); // Nothing happens
await emitter.emit('๐Ÿถ', 'b'); // Nothing happens
await emitter.emit('๐ŸฆŠ', 'c'); // Nothing happens
listener(data)

once(eventName | eventName[])

Subscribe to one or more events only once. It will be unsubscribed after the first event.

Returns a promise for the event data when eventName is emitted. This promise is extended with an off method.

import Emittery from 'emittery';

const emitter = new Emittery();

emitter.once('๐Ÿฆ„').then(data => {
	console.log(data);
	//=> '๐ŸŒˆ'
});

emitter.once(['๐Ÿฆ„', '๐Ÿถ']).then(data => {
	console.log(data);
});

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ'); // Log => '๐ŸŒˆ' x2
emitter.emit('๐Ÿถ', '๐Ÿ–'); // Nothing happens

events(eventName)

Get an async iterator which buffers data each time an event is emitted.

Call return() on the iterator to remove the subscription.

import Emittery from 'emittery';

const emitter = new Emittery();
const iterator = emitter.events('๐Ÿฆ„');

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ1'); // Buffered
emitter.emit('๐Ÿฆ„', '๐ŸŒˆ2'); // Buffered

iterator
	.next()
	.then(({value, done}) => {
		// done === false
		// value === '๐ŸŒˆ1'
		return iterator.next();
	})
	.then(({value, done}) => {
		// done === false
		// value === '๐ŸŒˆ2'
		// Revoke subscription
		return iterator.return();
	})
	.then(({done}) => {
		// done === true
	});

In practice, you would usually consume the events using the for await statement. In that case, to revoke the subscription simply break the loop.

import Emittery from 'emittery';

const emitter = new Emittery();
const iterator = emitter.events('๐Ÿฆ„');

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ1'); // Buffered
emitter.emit('๐Ÿฆ„', '๐ŸŒˆ2'); // Buffered

// In an async context.
for await (const data of iterator) {
	if (data === '๐ŸŒˆ2') {
		break; // Revoke the subscription when we see the value '๐ŸŒˆ2'.
	}
}

It accepts multiple event names.

import Emittery from 'emittery';

const emitter = new Emittery();
const iterator = emitter.events(['๐Ÿฆ„', '๐ŸฆŠ']);

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ1'); // Buffered
emitter.emit('๐ŸฆŠ', '๐ŸŒˆ2'); // Buffered

iterator
	.next()
	.then(({value, done}) => {
		// done === false
		// value === '๐ŸŒˆ1'
		return iterator.next();
	})
	.then(({value, done}) => {
		// done === false
		// value === '๐ŸŒˆ2'
		// Revoke subscription
		return iterator.return();
	})
	.then(({done}) => {
		// done === true
	});

emit(eventName, data?)

Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but executed concurrently.

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.

emitSerial(eventName, data?)

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.

If any of the listeners throw/reject, the returned promise will be rejected with the error and the remaining listeners will not be called.

onAny(listener)

Subscribe to be notified about any event.

Returns a method to unsubscribe.

listener(eventName, data)

offAny(listener)

Remove an onAny subscription.

anyEvent()

Get an async iterator which buffers a tuple of an event name and data each time an event is emitted.

Call return() on the iterator to remove the subscription.

import Emittery from 'emittery';

const emitter = new Emittery();
const iterator = emitter.anyEvent();

emitter.emit('๐Ÿฆ„', '๐ŸŒˆ1'); // Buffered
emitter.emit('๐ŸŒŸ', '๐ŸŒˆ2'); // Buffered

iterator.next()
	.then(({value, done}) => {
		// done === false
		// value is ['๐Ÿฆ„', '๐ŸŒˆ1']
		return iterator.next();
	})
	.then(({value, done}) => {
		// done === false
		// value is ['๐ŸŒŸ', '๐ŸŒˆ2']
		// Revoke subscription
		return iterator.return();
	})
	.then(({done}) => {
		// done === true
	});

In the same way as for events, you can subscribe by using the for await statement

clearListeners(eventNames?)

Clear all event listeners on the instance.

If eventNames is given, only the listeners for that events are cleared.

listenerCount(eventNames?)

The number of listeners for the eventNames or all events if not specified.

bindMethods(target, methodNames?)

Bind the given methodNames, or all Emittery methods if methodNames is not defined, into the target object.

import Emittery from 'emittery';

const object = {};

new Emittery().bindMethods(object);

object.emit('event');

TypeScript

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.

import Emittery from 'emittery';

const emitter = new Emittery<
	// Pass `{[eventName]: undefined | <eventArg>}` as the first type argument for events that pass data to their listeners.
	// 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.
	{
		open: string,
		close: undefined
	}
>();

// Typechecks just fine because the data type for the `open` event is `string`.
emitter.emit('open', 'foo\n');

// Typechecks just fine because `close` is present but points to undefined in the event data type map.
emitter.emit('close');

// TS compilation error because `1` isn't assignable to `string`.
emitter.emit('open', 1);

// TS compilation error because `other` isn't defined in the event data type map.
emitter.emit('other');

Emittery.mixin(emitteryPropertyName, methodNames?)

A decorator which mixins Emittery as property emitteryPropertyName and methodNames, or all Emittery methods if methodNames is not defined, into the target class.

import Emittery from 'emittery';

@Emittery.mixin('emittery')
class MyClass {}

const instance = new MyClass();

instance.emit('event');

Scheduling details

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.

Note that when using .emitSerial(), a slow listener will delay invocation of subsequent listeners. It's possible for newer events to overtake older ones.

Debugging

Emittery can collect and log debug information.

To enable this feature set the DEBUG environment variable to 'emittery' or '*'. Additionally you can set the static isDebugEnabled variable to true on the Emittery class, or myEmitter.debug.enabled on an instance of it for debugging a single instance.

See API for more details on how debugging works.

FAQ

How is this different than the built-in EventEmitter in Node.js?

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.

Isn't EventEmitter synchronous for a reason?

Mostly backwards compatibility reasons. The Node.js team can't break the whole ecosystem.

It also allows silly code like this:

let unicorn = false;

emitter.on('๐Ÿฆ„', () => {
	unicorn = true;
});

emitter.emit('๐Ÿฆ„');

console.log(unicorn);
//=> true

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.

Can you support multiple arguments for emit()?

No, just use destructuring:

emitter.on('๐Ÿฆ„', ([foo, bar]) => {
	console.log(foo, bar);
});

emitter.emit('๐Ÿฆ„', [foo, bar]);

Related

  • p-event - Promisify an event by waiting for it to be emitted

More Repositories

1

awesome

๐Ÿ˜Ž Awesome lists about all kinds of interesting topics
270,042
star
2

awesome-nodejs

โšก Delightful Node.js packages and resources
52,854
star
3

awesome-electron

Useful resources for creating apps with Electron
25,634
star
4

quick-look-plugins

List of useful Quick Look plugins for developers
17,497
star
5

got

๐ŸŒ Human-friendly and powerful HTTP request library for Node.js
TypeScript
14,218
star
6

type-fest

A collection of essential TypeScript types
TypeScript
14,015
star
7

ky

๐ŸŒณ Tiny & elegant JavaScript HTTP client based on the Fetch API
TypeScript
13,762
star
8

pure

Pretty, minimal and fast ZSH prompt
Shell
12,391
star
9

pageres

Capture website screenshots
TypeScript
9,573
star
10

ora

Elegant terminal spinner
JavaScript
8,591
star
11

np

A better `npm publish`
JavaScript
7,529
star
12

github-markdown-css

The minimal amount of CSS to replicate the GitHub Markdown style
CSS
7,421
star
13

caprine

Elegant Facebook Messenger desktop app
TypeScript
7,014
star
14

screenfull

Simple wrapper for cross-browser usage of the JavaScript Fullscreen API
HTML
6,891
star
15

Gifski

๐ŸŒˆ Convert videos to high-quality GIFs on your Mac
Swift
6,807
star
16

fkill-cli

Fabulously kill processes. Cross-platform.
JavaScript
6,782
star
17

query-string

Parse and stringify URL query strings
JavaScript
6,453
star
18

execa

Process execution for humans
JavaScript
6,019
star
19

modern-normalize

๐Ÿ’ Normalize browsers' default style
TypeScript
5,038
star
20

css-in-readme-like-wat

Style your readme using CSS with this simple trick
5,013
star
21

awesome-npm

Awesome npm resources and tips
4,315
star
22

promise-fun

Promise packages, patterns, chat, and tutorials
4,277
star
23

awesome-scifi

Sci-Fi worth consuming
4,268
star
24

electron-store

Simple data persistence for your Electron app or module - Save and load user preferences, app state, cache, etc
JavaScript
4,165
star
25

create-dmg

Create a good-looking DMG for your macOS app in seconds
JavaScript
3,950
star
26

speed-test

Test your internet connection speed and ping using speedtest.net from the CLI
JavaScript
3,882
star
27

eslint-plugin-unicorn

More than 100 powerful ESLint rules
JavaScript
3,877
star
28

ow

Function argument validation for humans
TypeScript
3,799
star
29

file-type

Detect the file type of a file, stream, or data
JavaScript
3,632
star
30

meow

๐Ÿˆ CLI app helper
JavaScript
3,305
star
31

p-queue

Promise queue with concurrency control
TypeScript
3,202
star
32

open

Open stuff like URLs, files, executables. Cross-platform.
JavaScript
2,976
star
33

Plash

๐Ÿ’ฆ Make any website your Mac desktop wallpaper
Swift
2,735
star
34

alfy

Create Alfred workflows with ease
JavaScript
2,570
star
35

trash

Move files and directories to the trash
JavaScript
2,512
star
36

fast-cli

Test your download and upload speed using fast.com
JavaScript
2,484
star
37

guides

A collection of succinct guides - Public Domain
2,424
star
38

globby

User-friendly glob matching
JavaScript
2,376
star
39

slugify

Slugify a string
JavaScript
2,357
star
40

emoj

Find relevant emoji from text on the command-line ๐Ÿ˜ฎ โœจ ๐Ÿ™Œ ๐Ÿด ๐Ÿ’ฅ ๐Ÿ™ˆ
JavaScript
2,311
star
41

cli-spinners

Spinners for use in the terminal
JavaScript
2,255
star
42

on-change

Watch an object or array for changes
JavaScript
1,966
star
43

devtools-detect

Detect if DevTools is open and its orientation
HTML
1,924
star
44

gulp-imagemin

Minify PNG, JPEG, GIF and SVG images
JavaScript
1,903
star
45

touch-bar-simulator

Use the Touch Bar on any Mac
Swift
1,900
star
46

notifier-for-github

Browser extension - Get notified about new GitHub notifications
JavaScript
1,828
star
47

editorconfig-sublime

Sublime Text plugin for EditorConfig - Helps developers maintain consistent coding styles between different editors
Python
1,757
star
48

is

Type check values
TypeScript
1,678
star
49

capture-website

Capture screenshots of websites
JavaScript
1,670
star
50

Defaults

๐Ÿ’พ Swifty and modern UserDefaults
Swift
1,661
star
51

electron-boilerplate

Boilerplate to kickstart creating an app with Electron
JavaScript
1,632
star
52

pageres-cli

Capture website screenshots
JavaScript
1,620
star
53

clipboardy

Access the system clipboard (copy/paste)
JavaScript
1,598
star
54

gulp-rev

Static asset revisioning by appending content hash to filenames: `unicorn.css` โ†’ `unicorn-d41d8cd98f.css`
JavaScript
1,538
star
55

pify

Promisify a callback-style function
JavaScript
1,494
star
56

boxen

Create boxes in the terminal
JavaScript
1,467
star
57

Actions

โš™๏ธ Supercharge your shortcuts
Swift
1,437
star
58

multiline

Multiline strings in JavaScript
JavaScript
1,424
star
59

hyper-snazzy

Elegant Hyper theme with bright colors
JavaScript
1,412
star
60

amas

Awesome & Marvelous Amas
1,392
star
61

LaunchAtLogin

Add โ€œLaunch at Loginโ€ functionality to your macOS app in seconds
Swift
1,346
star
62

del

Delete files and directories
JavaScript
1,316
star
63

refined-twitter

Browser extension that simplifies the Twitter interface and adds useful features
JavaScript
1,313
star
64

KeyboardShortcuts

โŒจ๏ธ Add user-customizable global keyboard shortcuts (hotkeys) to your macOS app in minutes
Swift
1,313
star
65

iterm2-snazzy

Elegant iTerm2 theme with bright colors
1,313
star
66

electron-context-menu

Context menu for your Electron app
JavaScript
1,297
star
67

p-limit

Run multiple promise-returning & async functions with limited concurrency
JavaScript
1,294
star
68

Settings

โš™ Add a settings window to your macOS app in minutes
Swift
1,282
star
69

trash-cli

Move files and folders to the trash
JavaScript
1,244
star
70

electron-util

Useful utilities for Electron apps and modules
JavaScript
1,188
star
71

is-online

Check if the internet connection is up
JavaScript
1,181
star
72

ponyfill

๐Ÿฆ„ Like polyfill but with pony pureness
1,136
star
73

conf

Simple config handling for your app or module
TypeScript
1,109
star
74

anatine

[DEPRECATED] ๐Ÿฆ Pristine Twitter app
JavaScript
1,097
star
75

electron-dl

Simplified file downloads for your Electron app
JavaScript
1,087
star
76

log-update

Log by overwriting the previous output in the terminal. Useful for rendering progress bars, animations, etc.
JavaScript
1,027
star
77

pretty-bytes

Convert bytes to a human readable string: 1337 โ†’ 1.34 kB
JavaScript
1,022
star
78

grunt-sass

Compile Sass to CSS
JavaScript
1,020
star
79

mem

Memoize functions - an optimization technique used to speed up consecutive function calls by caching the result of calls with identical input
TypeScript
1,019
star
80

DockProgress

Show progress in your app's Dock icon
Swift
1,003
star
81

wallpaper

Manage the desktop wallpaper
JavaScript
996
star
82

p-map

Map over promises concurrently
JavaScript
996
star
83

public-ip

Get your public IP address - very fast!
JavaScript
979
star
84

gulp-app

[DEPRECATED] Gulp as an app
JavaScript
961
star
85

grunt-shell

Run shell commands
JavaScript
952
star
86

load-grunt-tasks

Load multiple grunt tasks using globbing patterns
JavaScript
940
star
87

hasha

Hashing made simple. Get the hash of a buffer/string/stream/file.
JavaScript
934
star
88

pretty-ms

Convert milliseconds to a human readable string: `1337000000` โ†’ `15d 11h 23m 20s`
JavaScript
929
star
89

terminal-image

Display images in the terminal
JavaScript
923
star
90

object-assign

ES2015 Object.assign() ponyfill
JavaScript
922
star
91

copy-text-to-clipboard

Copy text to the clipboard in modern browsers (0.2 kB)
JavaScript
858
star
92

System-Color-Picker

๐ŸŽจ The macOS color picker as an app with more features
Swift
842
star
93

normalize-url

Normalize a URL
JavaScript
818
star
94

get-port

Get an available TCP port
JavaScript
817
star
95

atom-editorconfig

Helps developers maintain consistent coding styles between different editors
JavaScript
811
star
96

grunt-concurrent

Run grunt tasks concurrently
JavaScript
799
star
97

dot-prop

Get, set, or delete a property from a nested object using a dot path
JavaScript
777
star
98

p-progress

Create a promise that reports progress
TypeScript
751
star
99

gulp-changed

Only pass through changed files
JavaScript
747
star
100

generator-nm

Scaffold out a node module
JavaScript
742
star