Page functions Cotonic
Cotonics main functions are available in the cotonic namespace on the main page. The functions are mostly used to control and allow messaging between workers.
spawn cotonic.spawn(url, [args])
Spawn a new worker. The code of the worker should be available at url. The optional args parameter list will be passed to the worker and can be used to pass information from the page to the worker. It can be picked up with the on_init callback. The structured clone algorithm will be used to send the args to the worker. See worker functions for more information on implementing a worker. Returns the worker-id of the newly created worker process.
cotonic.spawn("/js/example-worker.js");
=> 1
cotonic.spawn("/js/another-worker.js", ["Arg1", 1]);
=> 2
spawn_named cotonic.spawn_named(name, src_url, [base], [args])
Spawn a new named worker. Named workers are unique. Use "" or undefined to create a nameless worker. Return the worker_id of the newly spawned worker. If the worker was already running, the existing worker_id is returned.
cotonic.spawn_named("example", "example-worker.js");
=> "worker"
exit cotonic.exit(nameOrwid)
Exit terminates a worker which was previously spawned and has nameOrWid as worker-id.
const wid = cotonic.spawn("example.worker.js");
cotonic.exit(wid);
=> Worker wid is no longer running.
send cotonic.send(nameOrWid, message)
Send message message to worker nameOrWid. The parameter nameOrWid can either be the name of worker, or a worker id. The structured clone algorithm will be used to copy the message before sending it to the worker.
cotonic.send(worker_id1, "hello");
receive cotonic.receive(handler)
Receive messages from workers. The handler should be a function which takes two parameters, the message, and the worker_id.
cotonic.receive(function(message, worker_id) {
console.log("Received", message, "from worker", worker_id);
});
Configuration
The page function has one configuration option.
- base_worker_src
- The url for the base worker runtime for cotonic. This runtime provides the required communication primitives.
<script>
window.cotonic = window.cotonic || {};
window.cotonic.config = {
base_worker_src: "/base/worker-bundle.js"
};
</script>
<script src="cotonic.js"></script>