diff --git a/lib/EventEmitter.js b/lib/EventEmitter.js index a88e55ae..c975abcf 100644 --- a/lib/EventEmitter.js +++ b/lib/EventEmitter.js @@ -11,14 +11,22 @@ export default class EventEmitter { } this.listeners[event].add(cb) + return this } emit (event, ...data) { - if (!this.listeners[event]) return - this.listeners[event].forEach(cb => cb(...data)) // eslint-disable-line standard/no-callback-literal + const listeners = this.listeners[event] + const hasListeners = listeners && listeners.size + if (!hasListeners) { + return false + } + + listeners.forEach(cb => cb(...data)) // eslint-disable-line standard/no-callback-literal + return true } off (event, cb) { this.listeners[event].delete(cb) + return this } } diff --git a/test/unit/EventEmitter.test.js b/test/unit/EventEmitter.test.js index 8699e419..8c04ca28 100644 --- a/test/unit/EventEmitter.test.js +++ b/test/unit/EventEmitter.test.js @@ -71,6 +71,30 @@ describe('EventEmitter', () => { expect(run).toThrow(/The listener already exising in event: sample/) }) + + it('should support chaining like the nodejs EventEmitter', () => { + const emitter = new EventEmitter() + let calledA = false + let calledB = false + + emitter + .on('a', () => { calledA = true }) + .on('b', () => { calledB = true }) + + emitter.emit('a') + emitter.emit('b') + + expect(calledA).toEqual(true) + expect(calledB).toEqual(true) + }) + + it('should return an indication on emit if there were listeners', () => { + const emitter = new EventEmitter() + emitter.on('a', () => { }) + + expect(emitter.emit('a')).toEqual(true) + expect(emitter.emit('b')).toEqual(false) + }) }) describe('Without a listener', () => {