|
| 1 | +class EventEmitter { |
| 2 | + constructor() { |
| 3 | + this.listeners = new Map() |
| 4 | + } |
| 5 | + on(event, cb, once = false) { |
| 6 | + if (!this.listeners.has(event)) { |
| 7 | + this.listeners.set( |
| 8 | + event, |
| 9 | + { |
| 10 | + callbacks: new Set, // use Set to register callback once |
| 11 | + once, |
| 12 | + } |
| 13 | + ) |
| 14 | + } |
| 15 | + this.listeners.get(event).callbacks.add(cb) |
| 16 | + |
| 17 | + return this // support chaining |
| 18 | + } |
| 19 | + once(event, cb) { |
| 20 | + const once = true |
| 21 | + this.on(event, cb, once) |
| 22 | + } |
| 23 | + off(event, cb) { |
| 24 | + if (!this.listeners.has(event)) return |
| 25 | + |
| 26 | + this.listeners.get(event).callbacks.delete(cb) |
| 27 | + |
| 28 | + return this |
| 29 | + } |
| 30 | + // TODO: check use cases for args and chaining, it looks dumb |
| 31 | + emit(event, ...args) { |
| 32 | + // check unregistered event |
| 33 | + if (!this.listeners.has(event)) return |
| 34 | + |
| 35 | + const {callbacks, once} = this.listeners.get(event) |
| 36 | + for (const cb of callbacks) { |
| 37 | + // support callback args |
| 38 | + cb(...args) |
| 39 | + } |
| 40 | + |
| 41 | + if (once) { |
| 42 | + this.listeners.delete(event) |
| 43 | + } |
| 44 | + |
| 45 | + return this |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +const emitter = new EventEmitter() |
| 50 | + |
| 51 | +function one () {console.log('one')} |
| 52 | +function two () {console.log('two')} |
| 53 | +function three () {console.log('three')} |
| 54 | +function doubleAndPrint (num, str) {console.log(num * 2, str)} |
| 55 | + |
| 56 | +emitter.on('run', one) |
| 57 | +emitter.on('run', two) |
| 58 | +emitter.on('run', two) |
| 59 | +emitter.on('run', three) |
| 60 | +emitter.on('run', doubleAndPrint) |
| 61 | +emitter.off('run', three) |
| 62 | + |
| 63 | +emitter.on('chain', three) |
| 64 | + .on('chain', two) |
| 65 | + .on('chain', one) |
| 66 | + .on('other', doubleAndPrint) |
| 67 | + .emit('other', 5 ,7) |
| 68 | + |
| 69 | +emitter.emit('run', 5, 7) |
| 70 | +emitter.emit('chain') |
| 71 | + |
| 72 | +emitter.once('onlyOnce', two) |
| 73 | +emitter.emit('onlyOnce') |
| 74 | +emitter.emit('onlyOnce') |
| 75 | +emitter.emit('onlyOnce') |
0 commit comments