From: gustavo Date: Wed, 18 May 2016 23:06:55 +0000 (+0200) Subject: Shared Worker, improvements X-Git-Url: https://git.gumartinm.name/?a=commitdiff_plain;h=796ea20e414cd31ad8a9eedeb2eba0efa2da9046;p=JavaScriptForFun Shared Worker, improvements --- 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); + }); +}