aboutsummaryrefslogtreecommitdiff
path: root/ext/js/core.js
diff options
context:
space:
mode:
authortoasted-nutbread <toasted-nutbread@users.noreply.github.com>2021-02-14 18:18:02 -0500
committerGitHub <noreply@github.com>2021-02-14 18:18:02 -0500
commit48b59375eb50a3c11ab1cbee659164e6991827ac (patch)
tree160bfe321492839cf3211b27285490e43a7f130d /ext/js/core.js
parent9279ced68660610764931da681f22c8b71bf1b6e (diff)
Cleanup yomichan api (#1394)
* Move invokeMessageHandler to core.js * Move getMessageResponseResult to backghend.js * Replace getTemporaryListenerResult
Diffstat (limited to 'ext/js/core.js')
-rw-r--r--ext/js/core.js36
1 files changed, 36 insertions, 0 deletions
diff --git a/ext/js/core.js b/ext/js/core.js
index 4384d9f0..9b95c407 100644
--- a/ext/js/core.js
+++ b/ext/js/core.js
@@ -342,6 +342,42 @@ function promiseAnimationFrame(timeout=null) {
}
/**
+ * Invokes a standard message handler. This function is used to react and respond
+ * to communication messages within the extension.
+ * @param handler A handler function which is passed `params` and `...extraArgs` as arguments.
+ * @param async Whether or not the handler is async or not. Values include `false`, `true`, or `'dynamic'`.
+ * When the value is `'dynamic'`, the handler should return an object of the format `{async: boolean, result: any}`.
+ * @param params Information which was passed with the original message.
+ * @param callback A callback function which is invoked after the handler has completed. The value passed
+ * to the function is in the format:
+ * * `{result: any}` if the handler invoked successfully.
+ * * `{error: object}` if the handler thew an error. The error is serialized.
+ * @param extraArgs Additional arguments which are passed to the `handler` function.
+ * @returns `true` if the function is invoked asynchronously, `false` otherwise.
+ */
+function invokeMessageHandler({handler, async}, params, callback, ...extraArgs) {
+ try {
+ let promiseOrResult = handler(params, ...extraArgs);
+ if (async === 'dynamic') {
+ ({async, result: promiseOrResult} = promiseOrResult);
+ }
+ if (async) {
+ promiseOrResult.then(
+ (result) => { callback({result}); },
+ (error) => { callback({error: serializeError(error)}); }
+ );
+ return true;
+ } else {
+ callback({result: promiseOrResult});
+ return false;
+ }
+ } catch (error) {
+ callback({error: serializeError(error)});
+ return false;
+ }
+}
+
+/**
* Base class controls basic event dispatching.
*/
class EventDispatcher {