Skip to content

Instantly share code, notes, and snippets.

@cambiata
Last active August 7, 2019 16:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cambiata/be0c2dc499da4be71151 to your computer and use it in GitHub Desktop.
Save cambiata/be0c2dc499da4be71151 to your computer and use it in GitHub Desktop.
-cp src
-js bin/Test.js
-main Test
-cp src
-js bin/WorkerScript.js
WorkerScript
Haxe Web Worker example based on David Mouton's code from this thread:
https://groups.google.com/d/msg/haxelang/id97u-SIGA0/snfI9hBJNkQJ
Compiles with Haxe 3.2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Workers2</title>
<meta name="description" content="" />
</head>
<body>
<p>Check the console for output!</p>
<script src="Test.js"></script>
</body>
</html>
package;
class Test
{
static function main()
{
var worker = new js.html.Worker('WorkerScript.js');
worker.onmessage = function(e) {
trace('Message from worker: ' + e.data);
}
worker.postMessage('Start');
worker.postMessage(123);
worker.postMessage('Hello');
worker.postMessage({name:'Bob'});
}
}
package;
class WorkerScript
{
public static function __init__() {
untyped __js__("onmessage = WorkerScript.prototype.messageHandler");
}
public function messageHandler(event) {
switch event.data {
// Do whatever...
// Here, for testing, we simply bounce back the data we got...
case _: postMessage(event.data);
}
}
// The following line seems to be needed only by the compiler...
public function postMessage(message) {}
}
// This is the compiled output of WorkerScript.hx, built with >haxe build-worker-script.hxml
(function (console) { "use strict";
var WorkerScript = function() { };
WorkerScript.prototype = {
messageHandler: function(event) {
var _g = event.data;
this.postMessage(event.data);
}
,postMessage: function(message) {
}
};
onmessage = WorkerScript.prototype.messageHandler;
})(typeof console != "undefined" ? console : {log:function(){}});
@elsassph
Copy link

elsassph commented Mar 1, 2019

Just wanted to suggest fixing the WorkerScript which is working "by chance" only:

class WorkerScript 
{
	static function __init__() {
 		var ws = new WorkerScript();
		untyped onmessage = ws.messageHandler;
	}

	public function messageHandler(event) {
		switch event.data {
			// Do whatever...
			// Here, for testing, we simply bounce back the data we got...
			case _: untyped postMessage(event.data);
		}
	}
}

Also the magic __init__ could be replaced by a regular -main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment