Fri, 16 Jan 2015 18:13:44 +0100
Integrate suggestion from review to improve consistency with existing code.
michael@0 | 1 | /** |
michael@0 | 2 | * Any copyright is dedicated to the Public Domain. |
michael@0 | 3 | * http://creativecommons.org/publicdomain/zero/1.0/ |
michael@0 | 4 | */ |
michael@0 | 5 | "use strict"; |
michael@0 | 6 | |
michael@0 | 7 | if (self.name != "FrameWorker") { |
michael@0 | 8 | throw new Error("Bad worker name: " + self.name); |
michael@0 | 9 | } |
michael@0 | 10 | |
michael@0 | 11 | var registeredPorts = []; |
michael@0 | 12 | var errorCount = 0; |
michael@0 | 13 | var storedData; |
michael@0 | 14 | |
michael@0 | 15 | self.onconnect = function(event) { |
michael@0 | 16 | var port = event.ports[0]; |
michael@0 | 17 | |
michael@0 | 18 | if (registeredPorts.length) { |
michael@0 | 19 | var data = { |
michael@0 | 20 | type: "connect" |
michael@0 | 21 | }; |
michael@0 | 22 | |
michael@0 | 23 | registeredPorts.forEach(function(registeredPort) { |
michael@0 | 24 | registeredPort.postMessage(data); |
michael@0 | 25 | }); |
michael@0 | 26 | } |
michael@0 | 27 | |
michael@0 | 28 | port.onmessage = function(event) { |
michael@0 | 29 | switch (event.data.command) { |
michael@0 | 30 | case "start": |
michael@0 | 31 | break; |
michael@0 | 32 | |
michael@0 | 33 | case "error": |
michael@0 | 34 | throw new Error("Expected"); |
michael@0 | 35 | |
michael@0 | 36 | case "store": |
michael@0 | 37 | storedData = event.data.data; |
michael@0 | 38 | break; |
michael@0 | 39 | |
michael@0 | 40 | case "retrieve": |
michael@0 | 41 | var data = { |
michael@0 | 42 | type: "result", |
michael@0 | 43 | data: storedData |
michael@0 | 44 | }; |
michael@0 | 45 | port.postMessage(data); |
michael@0 | 46 | break; |
michael@0 | 47 | |
michael@0 | 48 | default: |
michael@0 | 49 | throw new Error("Unknown command '" + error.data.command + "'"); |
michael@0 | 50 | } |
michael@0 | 51 | }; |
michael@0 | 52 | |
michael@0 | 53 | registeredPorts.push(port); |
michael@0 | 54 | }; |
michael@0 | 55 | |
michael@0 | 56 | self.onerror = function(message, filename, lineno) { |
michael@0 | 57 | if (!errorCount++) { |
michael@0 | 58 | var data = { |
michael@0 | 59 | type: "worker-error", |
michael@0 | 60 | message: message, |
michael@0 | 61 | filename: filename, |
michael@0 | 62 | lineno: lineno |
michael@0 | 63 | }; |
michael@0 | 64 | |
michael@0 | 65 | registeredPorts.forEach(function (registeredPort) { |
michael@0 | 66 | registeredPort.postMessage(data); |
michael@0 | 67 | }); |
michael@0 | 68 | |
michael@0 | 69 | // Prevent the error from propagating the first time only. |
michael@0 | 70 | return true; |
michael@0 | 71 | } |
michael@0 | 72 | }; |