From 123e725049e5c6b5c3b7b53ee37aaf93e7bb0c61 Mon Sep 17 00:00:00 2001 From: siikamiika Date: Sat, 4 Apr 2020 16:59:17 +0300 Subject: use duck typing for event listener --- ext/mixed/js/core.js | 49 ++++++++++++++++++++++++++----------------------- 1 file changed, 26 insertions(+), 23 deletions(-) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/core.js b/ext/mixed/js/core.js index 4314926c..7fb3c32e 100644 --- a/ext/mixed/js/core.js +++ b/ext/mixed/js/core.js @@ -325,34 +325,37 @@ const yomichan = (() => { reject = _reject; }); - if (eventHandler === chrome.runtime.onMessage) { - 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); - } + if ( + typeof eventHandler.addListener === 'undefined' || + typeof eventHandler.removeListener === 'undefined' + ) { + throw new Error('Event handler type not supported'); + } - const cleanupResolve = (value) => { - if (timeoutId !== null) { - window.clearTimeout(timeoutId); - timeoutId = null; - } + const runtimeMessageCallback = ({action, params}, sender, sendResponse) => { + let timeoutId = null; + if (timeout !== null) { + timeoutId = window.setTimeout(() => { + timeoutId = null; eventHandler.removeListener(runtimeMessageCallback); - sendResponse(); - resolve(value); - }; + reject(new Error(`Listener timed out in ${timeout} ms`)); + }, timeout); + } - userCallback({action, params}, {resolve: cleanupResolve, sender}); + const cleanupResolve = (value) => { + if (timeoutId !== null) { + window.clearTimeout(timeoutId); + timeoutId = null; + } + eventHandler.removeListener(runtimeMessageCallback); + sendResponse(); + resolve(value); }; - eventHandler.addListener(runtimeMessageCallback); - } else { - throw new Error('Event handler type not supported'); - } + userCallback({action, params}, {resolve: cleanupResolve, sender}); + }; + + eventHandler.addListener(runtimeMessageCallback); return listenerPromise; } -- cgit v1.2.3