mirror of
https://github.com/mozilla/gecko-dev.git
synced 2024-10-10 11:55:49 +00:00
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:
parent
039ad8df2d
commit
23ef0ad6b5
@ -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) {
|
||||
|
@ -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");
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
|
Loading…
Reference in New Issue
Block a user