use duck typing for event listener

This commit is contained in:
siikamiika 2020-04-04 16:59:17 +03:00
parent 067c26982e
commit 123e725049

View File

@ -325,35 +325,38 @@ const yomichan = (() => {
reject = _reject; reject = _reject;
}); });
if (eventHandler === chrome.runtime.onMessage) { if (
const runtimeMessageCallback = ({action, params}, sender, sendResponse) => { typeof eventHandler.addListener === 'undefined' ||
let timeoutId = null; typeof eventHandler.removeListener === 'undefined'
if (timeout !== null) { ) {
timeoutId = window.setTimeout(() => {
timeoutId = null;
eventHandler.removeListener(runtimeMessageCallback);
reject(new Error(`Listener timed out in ${timeout} ms`));
}, timeout);
}
const cleanupResolve = (value) => {
if (timeoutId !== null) {
window.clearTimeout(timeoutId);
timeoutId = null;
}
eventHandler.removeListener(runtimeMessageCallback);
sendResponse();
resolve(value);
};
userCallback({action, params}, {resolve: cleanupResolve, sender});
};
eventHandler.addListener(runtimeMessageCallback);
} else {
throw new Error('Event handler type not supported'); throw new Error('Event handler type not supported');
} }
const runtimeMessageCallback = ({action, params}, sender, sendResponse) => {
let timeoutId = null;
if (timeout !== null) {
timeoutId = window.setTimeout(() => {
timeoutId = null;
eventHandler.removeListener(runtimeMessageCallback);
reject(new Error(`Listener timed out in ${timeout} ms`));
}, timeout);
}
const cleanupResolve = (value) => {
if (timeoutId !== null) {
window.clearTimeout(timeoutId);
timeoutId = null;
}
eventHandler.removeListener(runtimeMessageCallback);
sendResponse();
resolve(value);
};
userCallback({action, params}, {resolve: cleanupResolve, sender});
};
eventHandler.addListener(runtimeMessageCallback);
return listenerPromise; return listenerPromise;
} }