diff options
author | Alex Yatskov <alex@foosoft.net> | 2016-03-24 20:56:47 -0700 |
---|---|---|
committer | Alex Yatskov <alex@foosoft.net> | 2016-03-24 20:56:47 -0700 |
commit | 059b2eb4f229f9669709520a5c88d041b3b64590 (patch) | |
tree | 9f53547aa6dd0ade22372dfc9f6c1298087a04b7 /ext | |
parent | ac012b26b37f6c01a80c1faa98fbe43913e47b6e (diff) |
Improved messaging
Diffstat (limited to 'ext')
-rw-r--r-- | ext/api.js | 6 | ||||
-rw-r--r-- | ext/content.js | 5 | ||||
-rw-r--r-- | ext/jp/api.js | 26 |
3 files changed, 28 insertions, 9 deletions
@@ -17,6 +17,10 @@ */ +function sendMessage(action, data, callback) { + window.chrome.runtime.sendMessage({action: action, data: data}, callback); +} + function findTerm(text, callback) { - window.chrome.runtime.sendMessage({action: 'define', text: text}, callback); + sendMessage('findTerm', {term: text}, callback); } diff --git a/ext/content.js b/ext/content.js index 5ff0031e..72e45337 100644 --- a/ext/content.js +++ b/ext/content.js @@ -53,4 +53,7 @@ function onMouseDown(e) { }); } -window.addEventListener('mousedown', onMouseDown, false); + +(() => { + window.addEventListener('mousedown', onMouseDown, false); +})(); diff --git a/ext/jp/api.js b/ext/jp/api.js index 3f15056a..95c2f7e3 100644 --- a/ext/jp/api.js +++ b/ext/jp/api.js @@ -17,11 +17,22 @@ */ +function onFindTerm({term}) { + return window.trans.findTerm(term); +} + function onMessage(request, sender, callback) { - switch (request.action.toLowerCase()) { - case 'define': - callback(window.trans.findTerm(request.text)); - break; + const {action, data} = request; + + const handler = { + findTerm: onFindTerm + }[action]; + + if (handler !== null) { + const result = handler(data); + if (callback !== null) { + callback(result); + } } } @@ -33,7 +44,8 @@ function onMessage(request, sender, callback) { kanjidic: 'jp/data/kanjidic.json' }; - window.trans = new Translator(res, function() { - chrome.runtime.onMessage.addListener(onMessage); - }); + window.trans = new Translator( + res, + () => chrome.runtime.onMessage.addListener(onMessage) + ); })(); |