@nfd/emitter

0.4.0 • Public • Published

Emitter

Installation · Usage · API

import emitter from '@nfd/emitter'

class Person {
  constructor(name) {
    this.name = name
  }
  meet(person) {
    this.emit('greet', {message: `Hello, ${person.name}!`})
  }
}
emitter(Person.prototype)

const alice = new Person('Alice')
const julia = new Person('Julia')

alice.on('greet', e => console.log('Alice says:', e.message))
julia.on('greet', e => console.log('Julia says:', e.message))

alice.meet(julia)
julia.meet(alice)

/* Alice says: Hello, Julia! */
/* Julia says: Hello, Alice! */

Installation

$ npm i @nfd/emitter

Usage

emitter(object) · class extends emitter { … } · new emitter

emitter(object)

Adds the emitter API methods to object (often, but not always, a class's prototype). Returns object.

const sara = emitter({name: 'Sara'})
sara.on('speak', console.log)
sara.emit('speak', 'Hello!')

/* Hello! */

class extends emitter { … }

The emitter function can also be used as a base class.

class Person extends emitter {
  constructor(name) {
    super()
    this.name = name
  }
}
const sara = new Person('Sara')
sara.on('speak', console.log)
sara.emit('speak', 'Hello!')

/* Hello! */

new emitter

Constructs an object with the emitter methods in its prototype chain.

const sara = new emitter
sara.on('speak', console.log)
sara.emit('speak', 'Hello!')

/* Hello! */

API

.on · .once · .off · .toggleListener · .listeners · .emit · .removeAllListeners

.on(event, fn[, context = undefined])

.addListener [alias]

Adds fn as a listener for event.

When event is emitted, fn is called with context as the this value. Duplicate listeners with the same (event, fn, context) triple are ignored (not called multiple times).

.once(event, fn[, context = undefined])

Adds fn as a listener only for the next emission of event (after which it is removed).

When event is emitted, fn is called with context as the this value. Duplicate listeners with the same (event, fn, context) triple are ignored (not called multiple times).

.off(event, fn[, context = undefined])

.removeListener [alias]

Removes fn with context context from the listeners for event.

.toggleListener(event, fn[, context = undefined], flag)

If flag is truthy, adds fn as a listener for event; otherwise, removes fn from the listeners for event.

.listeners(event)

Returns the list of listeners for event. Each listener is a record: {fn, context, once}.

.emit(event, arg)

Emits event, synchronously calling each associated listener with the argument arg.

.removeAllListeners([event])

Removes all listeners for event, or all listeners if event is unspecified.

Readme

Keywords

Package Sidebar

Install

npm i @nfd/emitter

Weekly Downloads

0

Version

0.4.0

License

MIT

Unpacked Size

7.01 kB

Total Files

4

Last publish

Collaborators

  • nfd