Module gamejs/worker
Workers are useful to relieve your GameJs application from code which might take long to run. Either expensive algorithms, which might get called every now and then (e.g., path-finding) or another logic being run continously within the rendering loop (e.g., physics engine).
A Worker is like a seperate GameJs application being executed - another main.js
with its own gamejs.ready()
. The Worker's most important feature is that code executing within it does not block the rendering code. The Worker's greatest limitation is that you can only communicate with it through text messages.
See the examples/workers
directory for a running example.
Example
// Create a worker with the main module "./test" var fooWorker = new Worker('./test'); // Send a message to your worker. // The Message doesn't have to be a string but it must be `JSON.stringify()`-able fooWorker.post("foobar"); fooWorker.onEvent(function(event) { if(event.data.timestamp > ...) }); // within the worker: you can send // send results back to the main application // by posting them:s gamejs.worker.post({ name: "zarzar", timestamp: 12232435234 });
Worker (moduleId)
The Worker
constructor takes only one argument: a module id. This module will be executed inside the newly created Worker. It is effectively the main module of the Worker.
Inside a Worker, you can use require()
to import other scripts or GameJs modules.
Note: A Worker does not have access to the browser's document
. So a lot of GameJs modules - everything related to drawing to the canvas - do not work in the Worker.
You can use gamejs.time.*
, gamejs.utils.*
, gamejs.event.*
and probably others (as well as any module you write yourself for this purpose, of course).
Parameters
String | moduleId | The Worker's main module id. The main module will be executed in the worker |
Worker.prototype.onError (fn, scope)
Parameters
fn | ||
scope |
Worker.prototype.onEvent (fn, scope)
Parameters
fn | ||
scope |
Worker.prototype.post (data)
Send a message to the worker
Parameters
Object | data | Payload object which gets sent to the Worker |
_EVENTS
ignore *
inWorker
true if this GameJs instance is being executed within a WebWorker
post (data)
Send an event back to the main script.
Parameters
Object | data | to be sent back to main script |