Skip to content

Instantly share code, notes, and snippets.

@fgarcia
Last active October 7, 2017 11:50
Show Gist options
  • Save fgarcia/043c1afac5a5b6ef6edd4aed739a8cb0 to your computer and use it in GitHub Desktop.
Save fgarcia/043c1afac5a5b6ef6edd4aed739a8cb0 to your computer and use it in GitHub Desktop.
Reset EventEmitter2
> node test.js
Start test
Catch!
end
Start test
Catch!
Catch!
end
Start test
Catch!
Catch!
Catch!
end
const {EventEmitter2} = require('eventemitter2')
let bus
bus = new EventEmitter2()
function reset_1() {
// fail !
bus.offAny()
}
function reset_2() {
bus._all = []
bus._events = {}
}
function reset_3() {
// WARNING
// this solves the test problem, but also breaks code which makes a copy of your bus.
//
// If you pass around instances of your bus, it is very likely you will break something
// if you just replace it with a new one
bus = new EventEmitter2()
}
function test() {
console.log('Start test')
// reset_1()
// WARNING
//
// You might be tempted to just test your code with 'once'. This however has two problems:
// 1. You will not notice unexpected extra calls
// 2. The code subscribing is out of your test, and it must always listen
bus.on('my-signal', () => {
console.log(' Catch!')
})
bus.emit('my-signal', 'hello')
console.log('end')
console.log()
console.log()
}
test()
test()
test()
@fgarcia
Copy link
Author

fgarcia commented Oct 7, 2017

Note to self: I've changed my mind

reset_3 might be the best solution after all. Currently reset_2 will break code which already subscribed to the previous bus. If you must reset your bus you also must reset objects depending on it. You might consider this type of reset:

bus.onAny( e => {
  throw Error('You are using an old instance of your bus')
})
bus = new EventEmitter2()

Notice that this will not solve your problems, it will just expose a lifecycle problem in your current code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment