diff --git a/devtools/shared/event-emitter.js b/devtools/shared/event-emitter.js index 0920f6fefb60..74aa87fd1756 100644 --- a/devtools/shared/event-emitter.js +++ b/devtools/shared/event-emitter.js @@ -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) { diff --git a/devtools/shared/tests/unit/test_eventemitter_basic.js b/devtools/shared/tests/unit/test_eventemitter_basic.js index 55c785403716..3283a3e5e676 100644 --- a/devtools/shared/tests/unit/test_eventemitter_basic.js +++ b/devtools/shared/tests/unit/test_eventemitter_basic.js @@ -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"); + }, }; /**