JFusco / es6-event-emitter

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

About

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

License:MIT License


Languages

Language:HTML 47.8%Language:JavaScript 37.8%Language:CSS 14.4%