on-one
Version:
Subscribe to one or more events and accept the first emitted
26 lines (25 loc) • 879 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;
const wrappers = [];
names.forEach((name)=>{
function wrapper(...args) {
if (called) return;
called = true;
// cleanup
for(let i = 0; i < names.length; i++){
emitter.removeListener(names[i], wrappers[i]);
}
// error-first callback: 'error' event passes error as first arg, others pass null
if (name === 'error') {
return fn(args[0], name);
}
return fn(null, ...args, name);
}
wrappers.push(wrapper);
emitter.on(name, wrapper);
});
}