Created
November 28, 2018 11:13
-
-
Save automagisch/a259d7d9b6f01114d772b8e1b9d7dec0 to your computer and use it in GitHub Desktop.
A simple approach to an event pattern. Used by extending it onto classes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
An event mocking class | |
- EventEmitter.events = { event: [], event2: [] ...etc } | |
- EventEmitter.on('event', d => console.log('adds callbacks with data as d (d=whatever)')) | |
! You can use EventEmitter.on('event event') to subscribe 1 callback to multiple events. note space separator | |
- EventEmitter.emit('event', (whatever)); // => runs callbacks from event[evt] added through ~.on(..^) | |
- Special: EventEmitter.on('*') will be emitted on any 'emit'. | |
*/ | |
export default class EventEmitter { | |
constructor() { | |
this.events={}; | |
} | |
on(e, cb) { | |
if(e.indexOf(' ') > -1) { | |
// subscribe space-separated events iterative | |
// (calls .on for each result on e splitted by spaces) | |
e = e.split(' ').forEach(ev => this.on(ev, cb)); | |
} else { | |
if(this.events[e]) { | |
this.events[e].push(cb); | |
} else { | |
this.events[e] = [cb]; | |
} | |
} | |
return this; | |
} | |
emit(e,d={},any=false) { | |
if(this.events[e]) { | |
this.events[e].forEach(cb => { | |
cb.call(this, d); | |
}); | |
} | |
if(!any) this.emit('*',e,true); | |
return this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment