on-one
Version:
Subscribe to one or more events and accept the first emitted
17 lines (16 loc) • 600 B
JavaScript
const isArray = Array.isArray || ((x)=>Object.prototype.toString.call(x) === '[object Array]');
export default function onOne(emitter, nameOrNames, fn) {
const names = isArray(nameOrNames) ? nameOrNames : [
nameOrNames
];
let called = false;
function wrapper() {
if (called) return;
called = true;
// cleanup
names.forEach((name)=>emitter.removeListener(name, wrapper));
// biome-ignore lint/complexity/noArguments: Apply arguments
return fn.apply(null, arguments);
}
names.forEach((name)=>emitter.on(name, wrapper));
}