Game Development Reference
In-Depth Information
The function is called when a message is received, both in the worker thread and in
its parent thread, and a MessageEvent object is passed to the function. This object
contains many attributes, including a timestamp, and most importantly, a data attrib-
ute, which contains any data passed into the worker.
To post a message to a worker or back to its parent, we simply call the function
postMessage on the appropriate object (either the worker object, or on the self-ob-
ject, if inside a worker), passing the data along with the function call. This data can
be a single value, an array, or an object of any type, as long as no functions are in-
cluded.
Finally, to create a worker object, we simply create an instance of the class Work-
er , passing the path to the worker script as a constructor parameter. This worker
object will need to register callback functions for whatever events it wants to observe:
onMessage or onError . To kill the worker thread, we can either call the termin-
ate function directly on the worker object, or the close function on the worker
script.
// index.html
var worker = new Worker("get-primes.worker.js");
worker.addEventListener("message",
function(event){
var primes = event.data.primes;
var ul = document.createElement("ul");
// Parse each prime returned from the worker
for (var i = 0, len = primes.length; i <
len; i++) {
var li = document.createElement("li");
li.textContent = primes[i];
ul.appendChild(li);
}
// Clear any existing list items
var uls = document.querySelectorAll("ul");
for (var i = 0, len = uls.length; i < len;
i++)
Search WWH ::




Custom Search