Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including @studiomoniker/emitter with all npm packages installed. Try it out:

var emitter = require("@studiomoniker/emitter")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

@studiomoniker/emitter v1.1.4

Browser / Node compatible ES6 event emitter loosely based on Node's implementation with added support for event forwarding and subscribing to all events.

emitter

Browser / Node compatible ES6 event emitter loosely based on Node's implementation with some added features:

  • Forward events from emitter to emitter: emitterA.on('event', emitterB)
  • Subscribe to all events: emitter.onAny((type, ...args) => doSomething(type, args))

Install

npm install @studiomoniker/emitter

Examples

Listening for and emitting events:

import Emitter from '@studiomoniker/emitter';

const emitter = new emitter();
emitter.on('foo', (message) => console.log(message));
emitter.emit('foo', 'bar');

Extending Emitter:

import Emitter from '@studiomoniker/emitter';

class Animal extends Emitter {
  makeSound(sound) {
    this.emit('a loud ' + sound);
  }
}

let animal = new Animal();
animal.on('sound', (sound) => {
  console.log(sound); // a loud growl
});
animal.makeSound('growl');

Adding and removing events:

import Emitter from '@studiomoniker/emitter';

function foo(message) {
  console.log('foo: ' + message);
}

const emitter = new Emitter();
emitter.on('foo', foo);
emitter.emit('foo', 'bar'); // Logs 'foo: bar'
emitter.off(foo);
emitter.emit('foo', 'bar'); // No longer logs 'foo: bar', because the listener was removed

Listen to all events:

import Emitter from '@studiomoniker/emitter';

function logAll(eventName, message) {
  console.log(`${eventName}: ${message}`);
}

const emitter = new Emitter();
emitter.onAny(foo);
emitter.emit('foo', 'bar'); // Logs 'foo: bar'
emitter.emit('poo', 'bar'); // Logs 'poo: bar'

Forward events:

import Emitter from '@studiomoniker/emitter';

function logAll(eventName, message) {
  console.log(`${eventName}: ${message}`);
}

const emitter = new Emitter();
const emitter2 = new Emitter();

// Forward 'message' events from emitter to emitter2:
emitter.on('message', emitter2);
emitter2.on('message', (message) => console.log('emitter2: ' + message));

emitter.emit('message', 'foo'); // Logs 'emitter2: foo'

Metadata

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free