Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make EventEmitter more Node-like #4865

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions lib/EventEmitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
24 changes: 24 additions & 0 deletions test/unit/EventEmitter.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down