Skip to content
Permalink
Browse files

feat: Support for arrays/sets to react to multiple events at the same…

… time
  • Loading branch information
martinheidegger committed Mar 31, 2019
1 parent 7815528 commit dc11860ade0cf10f32e675e37d8e8be46a0bacb1
Showing with 40 additions and 7 deletions.
  1. +1 −1 index.d.ts
  2. +19 −6 index.js
  3. +20 −0 test.js
@@ -2,4 +2,4 @@ import { EventEmitter } from 'events'

type StopListening = () => void

declare function hasListener (target: EventEmitter, event: string, handler: (hasHandler: boolean) => void): StopListening
declare function hasListener (target: EventEmitter, event: string | Array<string> | Set<string>, handler: (hasHandler: boolean) => void): StopListening
@@ -1,17 +1,17 @@
'use strict'

function createCounter (targetEvent, count, handler) {
function createCounter (targetEvents, count, handler) {
handler(count > 0)
return {
up (event) {
if (event !== targetEvent) return
if (!targetEvents.has(event)) return
count += 1
if (count === 1) {
handler(true)
}
},
down (event) {
if (event !== targetEvent) return
if (!targetEvents.has(event)) return
count -= 1
if (count === 0) {
handler(false)
@@ -20,9 +20,22 @@ function createCounter (targetEvent, count, handler) {
}
}

exports.hasListener = function hasListener (target, targetEvent, handler) {
let counter = createCounter(targetEvent, target.listenerCount(targetEvent), handler)
target.listenerCount(targetEvent)
function countListeners (target, targetEvents) {
let count = 0
for (const targetEvent of targetEvents) {
count += target.listenerCount(targetEvent)
}
return count
}

exports.hasListener = function hasListener (target, targetEvents, handler) {
if (!(targetEvents instanceof Set)) {
if (!Array.isArray(targetEvents)) {
targetEvents = [targetEvents]
}
targetEvents = new Set(targetEvents)
}
let counter = createCounter(targetEvents, countListeners(target, targetEvents), handler)
target.on('newListener', counter.up)
target.on('removeListener', counter.down)

20 test.js
@@ -30,3 +30,23 @@ test('Basic functionality', t => {
t.equals(count, 4, 'after stopping the trigger shouldnt be called')
t.end()
})

test('multiple events', t => {
const emitter = new EventEmitter()
let active = null
hasListener(emitter, ['a', 'b'], isActive => {
active = isActive
})
t.equals(active, false, 'no listener yet!')
emitter.on('a', () => {})
t.equals(active, true, 'one listener is enough')
emitter.removeAllListeners('a')
t.equals(active, false, 'but one is needed!')
emitter.on('b', () => {})
t.equals(active, true, 'the other listener also works')
emitter.on('a', () => {})
t.equals(active, true, 'two listeners work as well')
t.removeAllListeners('b')
t.equals(active, true, 'back to one, still okay!')
t.end()
})

0 comments on commit dc11860

Please sign in to comment.
You can’t perform that action at this time.