All Projects → necolas → emitter.js

necolas / emitter.js

Licence: MIT license
A simple JavaScript event-emitter

Programming Languages

javascript
184084 projects - #8 most used programming language
Makefile
30231 projects

emitter.js

unmaintained

Build Status

JavaScript event-emitter.

Installation

npm: npm install emitter.js Component(1): component install necolas/emitter.js Bower: bower install emitter.js

API

Emitter(obj)

The Emitter function can be used as a Constructor or as a mixin.

As an Emitter instance:

var Emitter = require('emitter');
var foo = new Emitter;
foo.trigger('foo');

As a mixin:

var Emitter = require('emitter');
var foo = {};
Emitter(foo);

foo.trigger('bar');

As a prototype mixin:

var Emitter = require('emitter');
var Foo = function () {};
Emitter(Foo.prototype);

Emitter#on(event, callback)

Register an event handler callback. Protects against duplicate handlers being registered.

var handler = function () {
  console.log('The function `handler` has been registered for the event `foo`.');
};

foo.on('foo', handler);

Emitter#once(event, callback)

Register a one-off event handler callback, removed immediately after it is invoked the first time.

var handler = function () {
  console.log('The function `handler` has been registered as a one-off callback for the event `foo`.');
};

foo.once('foo', handler);

Emitter#off([event], [callback])

Remove the event handler callback. If no callback is specified, it will remove all callbacks for the event. If no event is specified, the entire event registry will be deleted.

var handler = function () {
  console.log('Registered for the event `foo`.');
};

foo.off('foo', handler);
foo.off('foo');
foo.off();

Emitter#trigger(event, [...])

Trigger an event with optional arguments. Alias: emit.

var data = { name: 'nicolas' };
foo.trigger('foo', data);

Emitter#getListeners(event)

Return an array of callbacks registered for the event, or an empty array. Initializes the registry if necessary.

foo.getListeners('foo');

Emitter#hasListeners(event)

Check if any callbacks are registered for the event.

foo.hasListeners('foo');

Testing

Install and run the test suite:

make

Re-run the test suite:

make test

Browser support

  • Google Chrome (latest)
  • Opera (latest)
  • Firefox 4+
  • Safari 5+
  • Internet Explorer 8+
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].