# hook-emitter

> Event emitter with support for asynchronous handlers and a sweet function hook mechanism.

Latest version **6.0.0** (published 2022-03-01) · MIT license · 0 weekly downloads

## Install

```sh
npm install hook-emitter
pnpm add hook-emitter
yarn add hook-emitter
bun add hook-emitter
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: esm support; no vulnerabilities.

Warnings: low downloads; no types.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 6.0.0 |
| Published | 2022-03-01 |
| First published | 2016-02-18 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | ESM |
| Node | >=14.15.0 |
| Dependencies | 0 |
| Unpacked size | 18 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 9 |
| Author | Chris Barber |
| Maintainers | cb1kenobi |
| Keywords | hook, emitter, event, eventemitter, events, async, promise, promises, chain, link |

## Links

- npm: https://www.npmjs.com/package/hook-emitter
- Repository: https://github.com/cb1kenobi/hook-emitter
- Issues: https://github.com/cb1kenobi/hook-emitter/issues
- npm.io page: https://npm.io/package/hook-emitter

## Alternatives

- [async-exit-hook](https://npm.io/package/async-exit-hook.md) — 3.7M weekly downloads
- [evnty](https://npm.io/package/evnty.md) — 7.2K weekly downloads
- [eleventy-plugin-asciidoc](https://npm.io/package/eleventy-plugin-asciidoc.md) — 3.5K weekly downloads
- [@jswork/next-get2get](https://npm.io/package/@jswork/next-get2get.md) — 945 weekly downloads
- [@dashersw/axon](https://npm.io/package/@dashersw/axon.md) — 934 weekly downloads

## Recent versions

- 6.0.0 (latest) — 2022-03-01
- 5.0.0 — 2021-02-23
- 4.1.2 — 2021-02-23
- 4.1.1 — 2020-11-20
- 4.1.0 — 2020-05-01
- 4.0.2 — 2020-03-07
- 4.0.1 — 2020-01-07
- 4.0.0 — 2019-07-09
- 3.1.2 — 2018-12-13
- 3.1.1 — 2018-09-26
- 3.1.0 — 2018-09-23
- 3.0.2 — 2018-07-11
- 3.0.1 — 2018-06-12
- 3.0.0 — 2018-05-30
- 2.1.0 — 2017-05-24
- … 10 more at https://npm.io/package/hook-emitter/versions

## README

# hook-emitter

[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]

Promised-based chained event emitter with ability to create hooks around functions.

## Installation

    npm i hook-emitter --save

## Examples

Async listener example:

```js
import HookEmitter from 'hook-emitter';

const emitter = new HookEmitter();

emitter.on('sum', (x, y) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('the sum of ' + x + ' + ' + y + ' = ' + (x + y));
            resolve();
        }, 100);
    });
});

// emit and wait for all listeners to be called
await emitter.emit('sum', 3, 7);
```

Hook example:

```js
const emitter = new HookEmitter();

const hookedSum = emitter.hook('sum', (x, y) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            // x = 6, y = 14
            resolve(x + y);
        }, 100);
    });
});

emitter.on('sum', function (x, y) {
    console.log('doubling x and y');
    this.args[0] *= 2;
    this.args[1] *= 2;
});

emitter.on('sum', async (x, y, next) => {
	console.log('doubling result after sum function has been called');
	const r = await next();
	r.result *= 2;
	return r;
});

const result = await hookedSum(3, 7);
console.log('The sum of (6 + 14) * 2 = ' + result);
```

Chaining multiple hooked functions example:

```js
const emitter = new HookEmitter();

await emitter.hook('step1', () => {
    console.log('step 1');
})();

await emitter.hook('step2', () => {
    console.log('step 2');
})();

await emitter.hook('step3', () => {
    console.log('step 3');
})();
```

## API

### Constructor

The `HookEmitter` constructor takes no arguments.

### Properties

#### `events`

A `Map` object of event names to arrays of listener functions. This can be iterated
over using a for-of loop.

### Methods

#### `on(event, listener)`
#### `on(event, priority=0, listener)`

Adds an event listener. Returns `this`.

 * `event` String - One or more space-separated event names to add the listener to.
 * `priority` Number (optional) - Defaults to `0`. The higher the priority, the
   sooner the listener is called. Value may be negative.
 * `listener` Function - A function to call when the event is emitted.

#### `once(event, listener)`
#### `once(event, priority=0, listener)`

Adds an event listener that will only be called once. Returns `this`.

 * `event` String - One or more space-separated event names to add the listener to.
 * `priority` Number (optional) - Defaults to `0`. The higher the priority, the
   sooner the listener is called. Value may be negative.
 * `listener` Function - A function to call when the event is emitted.

#### `off(event, listener)`

Removes an event listener. Returns `this`.

 * `event` String - One or more space-separated event names to remove the listener from.
 * `listener` Function (optional) - The listener function. If not specified,
   then all listeners for the specified event are removed.

#### `emit(event, ...args)`

Emits one or more events. Returns a `Promise`.

 * `event` String - The name of the event to emit.
 * `args` * (optional) - One or more additional arguments to be emitted with the event.

#### `hook(event, ctx, fn)`

Creates a function hook. Returns a `Function` which when called returns a `Promise`.

 * `event` String - The name of the hook's event.
 * `ctx` Object (optional) - The context to run the function in. Useful if `fn` is
   going to be overwritten.
 * `fn` Function - The function being hooked up.

Hook listeners are passed the same input arguments plus a `next()` callback.
For example, if the hooked function accepts two arguments `x` and `y`, then the
listeners will be called with `x`, `y`, and `next`. A listener only needs to
call `next()` if it wishes be invoked after the hooked function has been called.

Listener functions are called in the context of the hook event meaning they can
access:

 * `this.type` String - The name of the event.
 * `this.args` Array - The same arguments that the listener is invoked with. This
   is useful if you want to modify the arguments being passed to the hooked
   function.
 * `this.fn` Function - The hooked function. You can use this to completely
   replace the hooked function.
 * `this.result` * - The result from the hooked function. If the hooked function
   is async, then this will be `undefined` and the actual result will be returned
   by the promise chain.

```js
emitter.on('foo', function (x, y, next) {
	console.log('event type:', this.type);
	console.log('args:', this.args);
	console.log('fn:', this.fn);

	// you can modify the args like this:
	this.args = [y, x];
});
```

#### `link(emitter, prefix)`

Links another `HookEmitter` to this instance. Useful if you have a class that
extends a `HookEmitter`, then another `HookEmitter` that you want to receive
the exact same events.

 * `emitter` HookEmitter - The hook emitter to link to this instance.
 * `prefix` String (optional) - An optional prefix to prepend to the event name
   being emitted from all linked emitters.

#### `unlink(emitter)`

Unlinks another `HookEmitter` from this instance. It does the opposite of
`link()`.

 * `emitter` HookEmitter - The hook emitter to unlink.

## License

MIT

[npm-image]: https://img.shields.io/npm/v/hook-emitter.svg
[npm-url]: https://npmjs.org/package/hook-emitter
[downloads-image]: https://img.shields.io/npm/dm/hook-emitter.svg
[downloads-url]: https://npmjs.org/package/hook-emitter

---
_Source: https://npm.io/package/hook-emitter · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
