Skip to content

Custom, simple, extendable event/messaging system written in ES6

License

Notifications You must be signed in to change notification settings

JFusco/es6-event-emitter

Repository files navigation

es6-event-emitter

Build Status

devDependency Status

MIT npm

Custom, simple, extendable event/messaging system written in ES6

Getting Started

Installation

From the root of your project.

npm install es6-event-emitter --save

Usage

Simple implementation of emitter. See api below.

import Emitter from 'es6-event-emitter';

export default class Component extends Emitter {
	constructor(){
		super();
	}

	//-- Trigger
	someAction(){
		...

		this.trigger('component:action');
	}

	//-- Trigger with data
	someOtherAction(){
		...

        this.trigger('component:otheraction', {
            foo: 'bar',
            baz: 'buzz'
        });
    }
}

//-- Create a new component
const component = new Component();

//-- Set up functions for listeners - best practice in case you want to remove them later.
const action = () => {
	console.log('action triggered');
}

const otheraction = data => {
	console.log(`other action triggered with data ${data}`);
}

//-- Register listeners
component.on('component:action', action);
component.on('component:otheraction', otheraction);

//-- Call methods
component.someAction();
component.someOtherAction();

API

on - on(event:String, callback:Function)

Registers a listener

component.on('component:action', action);

off - off(event:String, callback:Function)

Removes a registered listener from the event stack

component.off('component:action', action);

once - once(event:String, callback:Function)

Registers a listener that will only fire once no matter how many times you try to trigger

component.once('component:action', action);

trigger - trigger(event:String, ...args:*)

Triggers a registered event with optional data

this.trigger('component:action');

//-- With data
this.trigger('component:action', {
    foo: 'bar',
    baz: 'buzz'
});

destroy - destroy()

Destroys the entire event emitter

component.destroy();

Tests

View the test coverage

npm test