Skip to content

Instantly share code, notes, and snippets.

@pmuellr
Created February 2, 2017 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmuellr/81e899d769e7ef9cea2a7e790087da53 to your computer and use it in GitHub Desktop.
Save pmuellr/81e899d769e7ef9cea2a7e790087da53 to your computer and use it in GitHub Desktop.
test if the function passed to ee.on() and ee.removeListener() can validly be "inner functions"
'use strict'
// Not sure how valid this test is, but the attempt is to try to see if
// the function passed to ee.on() and ee.removeListener() can validly be
// "inner functions". Specifically, does the ee class consider `onEmitted()`
// functions to be different based on their closure. You would hope yes, and
// I think that's what the test shows.
//
// If they weren't considered different, instead of the listener list shrinking
// from both ends, it would shrink from just one end.
const EventEmitter = require('events')
class Emitter extends EventEmitter {
constructor () {
super()
let counter = 0
setInterval(() => {
counter++
console.log('')
this.emit('emitted', counter)
}, 1000).unref()
}
}
const ListenerCount = 5
const emitter = new Emitter()
for (let i = 1; i <= ListenerCount; i++) {
createListener(i)
}
for (let i = ListenerCount; i >= 1; i--) {
createListener(i)
}
function createListener (i) {
emitter.on('emitted', onEmitted)
setTimeout(stop, i * 1010)
function onEmitted (counter) {
console.log(`listener ${i}: ${counter}`)
}
function stop () {
emitter.removeListener('emitted', onEmitted)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment