Use static object for frontend message handlers

This commit is contained in:
toasted-nutbread 2019-10-02 20:31:42 -04:00
parent a628610cbd
commit 7d15213916

View File

@ -55,7 +55,7 @@ class Frontend {
try { try {
this.options = await apiOptionsGet(this.getOptionsContext()); this.options = await apiOptionsGet(this.getOptionsContext());
window.addEventListener('message', this.onFrameMessage.bind(this)); window.addEventListener('message', this.onWindowMessage.bind(this));
window.addEventListener('mousedown', this.onMouseDown.bind(this)); window.addEventListener('mousedown', this.onMouseDown.bind(this));
window.addEventListener('mousemove', this.onMouseMove.bind(this)); window.addEventListener('mousemove', this.onMouseMove.bind(this));
window.addEventListener('mouseover', this.onMouseOver.bind(this)); window.addEventListener('mouseover', this.onMouseOver.bind(this));
@ -71,7 +71,7 @@ class Frontend {
window.addEventListener('contextmenu', this.onContextMenu.bind(this)); window.addEventListener('contextmenu', this.onContextMenu.bind(this));
} }
chrome.runtime.onMessage.addListener(this.onBgMessage.bind(this)); chrome.runtime.onMessage.addListener(this.onRuntimeMessage.bind(this));
} catch (e) { } catch (e) {
this.onError(e); this.onError(e);
} }
@ -135,20 +135,12 @@ class Frontend {
this.popupTimerClear(); this.popupTimerClear();
} }
onFrameMessage(e) { onWindowMessage(e) {
const handlers = { const action = e.data;
popupClose: () => { const handlers = Frontend.windowMessageHandlers;
this.searchClear(true); if (handlers.hasOwnProperty(action)) {
}, const handler = handlers[action];
handler(this);
selectionCopy: () => {
document.execCommand('copy');
}
};
const handler = handlers[e.data];
if (handler) {
handler();
} }
} }
@ -240,20 +232,11 @@ class Frontend {
this.contextMenuChecking = false; this.contextMenuChecking = false;
} }
onBgMessage({action, params}, sender, callback) { onRuntimeMessage({action, params}, sender, callback) {
const handlers = { const handlers = Frontend.runtimeMessageHandlers;
optionsUpdate: () => { if (handlers.hasOwnProperty(action)) {
this.updateOptions();
},
popupSetVisible: ({visible}) => {
this.popup.setVisible(visible);
}
};
const handler = handlers[action]; const handler = handlers[action];
if (handler) { handler(this, params);
handler(params);
callback(); callback();
} }
} }
@ -529,4 +512,25 @@ class Frontend {
} }
} }
Frontend.windowMessageHandlers = {
popupClose: (self) => {
self.searchClear(true);
},
selectionCopy: () => {
document.execCommand('copy');
}
};
Frontend.runtimeMessageHandlers = {
optionsUpdate: (self) => {
self.updateOptions();
},
popupSetVisible: (self, {visible}) => {
self.popup.setVisible(visible);
}
};
window.yomichan_frontend = Frontend.create(); window.yomichan_frontend = Frontend.create();