Bug 1603035 - Return a function from EventEmitter.on that removes the event listener when called. r=rcaliman.

This will be helpful when consumers don't want to
keep the target around.
A test is added to ensure this work as expected (and
was failing if the returned function does not call
EventEmitter.off).

Differential Revision: https://phabricator.services.mozilla.com/D56685

--HG--
extra : moz-landing-system : lando
This commit is contained in:
Nicolas Chevobbe 2019-12-13 13:55:23 +00:00
parent 039ad8df2d
commit 23ef0ad6b5
2 changed files with 20 additions and 1 deletions

View File

@ -28,6 +28,8 @@ class EventEmitter {
* The type of event.
* @param {Function|Object} listener
* The listener that processes the event.
* @returns {Function}
* A function that removes the listener when called.
*/
static on(target, type, listener) {
if (typeof listener !== "function" && !isEventHandler(listener)) {
@ -45,6 +47,8 @@ class EventEmitter {
} else {
events.set(type, new Set([listener]));
}
return () => EventEmitter.off(target, type, listener);
}
/**
@ -253,7 +257,7 @@ class EventEmitter {
}
on(...args) {
EventEmitter.on(this, ...args);
return EventEmitter.on(this, ...args);
}
off(...args) {

View File

@ -255,6 +255,21 @@ const TESTS = {
emitter.emit("c", 1);
equal(received.length, 3, "the listener was not called after clearEvents");
},
testOnReturn() {
const emitter = getEventEmitter();
let called = false;
const removeOnTest = emitter.on("test", () => {
called = true;
});
equal(typeof removeOnTest, "function", "`on` returns a function");
removeOnTest();
emitter.emit("test");
equal(called, false, "event listener wasn't called");
},
};
/**