all files / src/ emitter.js

100% Statements 60/60
93.33% Branches 28/30
100% Functions 12/12
100% Lines 44/44
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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102     14× 14×       14×     13× 13×     12×     11× 11×         11×   11×                                     14× 14×     13× 13×   13×             13×                     59×            
const emitter = new WeakMap();
 
class Emitter {
	constructor(){
		emitter.set(this, {
			events: {}
		});
 
		this.eventLength = 0;
	}
 
	on(event, cb, once = false){
		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,
      once
    });
 
		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 === 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.');
		}
 
		const listeners = this.events[event];
    const onceListeners = [];
 
		if(typeof listeners !== 'undefined') {
			listeners.forEach((v, k) => {
        v.cb.apply(this, args);
 
        if(v.once) onceListeners.unshift(k);
 
        onceListeners.forEach((v, k) => {
          listeners.splice(k, 1);
        });
			});
		}
 
		return this;
	}
 
  once(event, cb){
    this.on(event, cb, true);
  }
 
  destroy(){
    emitter.delete(this);
 
    this.eventLength = 0;
  }
 
	get events(){
		return emitter.get(this).events;
	}
}
 
export default Emitter;