1
是否有可能在網絡工作者中註冊偵聽器到'message'
和'error'
以外的事件?例如。在網絡工作者中註冊事件偵聽器
addEventListener('keydown', function (e) {
postMessage('test');
});
編輯:
據@ T.J.Crowder,這是不可能的。然而,在我的情況,我能夠用消息來模擬它,不知何故像這樣:
在工人:
const handlers = {};
function registerKeyHandler(keycode, callback) {
postMessage({
type: 'REGISTER_KEY_HANDLER',
keycode: keycode,
});
handlers[keycode] = handlers[keycode] || [];
handlers[keycode].push(callback);
}
function onKeydown(keycode) {
const hs = handlers[keycode] || [];
hs.forEach(h => h());
}
self.onmessage = function(msg) {
switch (msg.type) {
case 'KEYDOWN':
onKeydown(msg.payload.keycode);
break;
}
};
外:
worker.onmessage = function(msg) {
switch (msg.type) {
case 'REGISTER_KEY_HANDLER':
window.addEventListener('keydown', function (e) {
if (e.keyCode !== msg.keycode) {
return;
}
worker.postMessage({
type: 'KEYDOWN',
keycode: msg.keycode,
});
});
break;
}
};