Last active
October 7, 2017 11:50
-
-
Save fgarcia/043c1afac5a5b6ef6edd4aed739a8cb0 to your computer and use it in GitHub Desktop.
Reset EventEmitter2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> node test.js | |
Start test | |
Catch! | |
end | |
Start test | |
Catch! | |
Catch! | |
end | |
Start test | |
Catch! | |
Catch! | |
Catch! | |
end | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
Notice that this will not solve your problems, it will just expose a lifecycle problem in your current code.