From 796ea20e414cd31ad8a9eedeb2eba0efa2da9046 Mon Sep 17 00:00:00 2001 From: gustavo Date: Thu, 19 May 2016 01:06:55 +0200 Subject: [PATCH] Shared Worker, improvements --- ecma6/sharedworkers/main.js | 6 +++++- ecma6/sharedworkers/shared.js | 44 +++++++++++++++++++++---------------------- 2 files changed, 27 insertions(+), 23 deletions(-) diff --git a/ecma6/sharedworkers/main.js b/ecma6/sharedworkers/main.js index 5c3687e..887aee6 100644 --- a/ecma6/sharedworkers/main.js +++ b/ecma6/sharedworkers/main.js @@ -31,7 +31,11 @@ } function onMessage(event) { - log.insertAdjacentHTML('beforeend', 'Message received from worker: ' + event.data + '
'); + if (event.data.error) { + log.insertAdjacentHTML('beforeend', 'Error received from worker: ' + event.data.error + '
'); + } else { + log.insertAdjacentHTML('beforeend', 'Message received from worker: ' + event.data + '
'); + } } function onError() { diff --git a/ecma6/sharedworkers/shared.js b/ecma6/sharedworkers/shared.js index fa4005f..a301838 100644 --- a/ecma6/sharedworkers/shared.js +++ b/ecma6/sharedworkers/shared.js @@ -3,27 +3,9 @@ var lastData; var messagePorts = []; -onconnect = function(event) { +self.onconnect = function(event) { var messagePort = event.ports[0]; - messagePort.onmessage = function(event) { - - var workerResult; - if (lastData) { - workerResult = 'Result: ' + event.data + ' Last data: ' + lastData; - } else { - workerResult = 'Result: ' + event.data; - } - lastData = event.data; - - console.log('SharedWorkerGlobalScope name: ' + name); - console.log('SharedWorkerGlobalScope location: ' + location); - console.log('SharedWorkerGlobalScope result: ' + event.data); - - messagePorts.forEach(function (messagePort) { - messagePort.postMessage(workerResult); - }); - }; - + messagePort.onmessage = onMessage; messagePorts.push(messagePort); // When and where should I call close method? @@ -32,6 +14,24 @@ onconnect = function(event) { }; -onerror = function() { - console.log('SharedWorkerGlobalScope: There is an error with the shared worker!'); +self.onerror = function() { + self.console.log('SharedWorkerGlobalScope: There is an error with the shared worker!'); }; + +function onMessage(event) { + var workerResult; + if (lastData) { + workerResult = 'Result: ' + event.data + ' Last data: ' + lastData; + } else { + workerResult = 'Result: ' + event.data; + } + lastData = event.data; + + self.console.log('SharedWorkerGlobalScope name: ' + self.name); + self.console.log('SharedWorkerGlobalScope location: ' + self.location); + self.console.log('SharedWorkerGlobalScope result: ' + event.data); + + messagePorts.forEach(function (messagePort) { + messagePort.postMessage(workerResult); + }); +} -- 2.1.4