all files / src/ emitter.js

100% Statements 52/52
91.67% Branches 22/24
100% Functions 9/9
100% Lines 37/37
1 branch Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85        12× 12×       12×       11×     10×                                             12× 12×     11×   11×               50×          
'use strict';
 
const emitter = new WeakMap();
 
class Emitter {
	constructor(){
		emitter.set(this, {
			events: {}
		});
 
		this.eventLength = 0;
	}
 
	on(event, cb){
		if(typeof cb === 'undefined') {
			throw new Error('You must provide a callback method.');
		}
 
		if(typeof cb !== 'function') {
			throw new TypeError('Listener must be a function');
		}
 
		this.events[event] = this.events[event] || [];
		this.events[event].push(cb);
 
		this.eventLength++;
 
		return this;
	}
 
	off(event, cb){
		if(typeof cb === 'undefined') {
			throw new Error('You must provide a callback method.');
		}
 
		if(typeof cb !== 'function') {
			throw new TypeError('Listener must be a function');
		}
 
		if(typeof this.events[event] === 'undefined'){
			throw new Error(`Event not found - the event you provided is: ${event}`);
		}
 
		const listeners = this.events[event];
 
		listeners.forEach((v, i) => {
			Eif(v === cb) {
				listeners.splice(i, 1);
			}
		});
 
		Eif(listeners.length === 0){
			delete this.events[event];
 
			this.eventLength--;
		}
 
		return this;
	}
 
	trigger(event, ...args){
		if(typeof event === 'undefined'){
			throw new Error('You must provide an event to trigger.');
		}
 
		let listeners = this.events[event];
 
		if(typeof listeners !== 'undefined') {
			listeners = listeners.slice(0);
 
			listeners.forEach((v) => {
				v.apply(this, args);
			});
		}
 
		return this;
	}
 
	get events(){
		return emitter.get(this).events;
	}
}
 
export default Emitter;