Skip to content

Instantly share code, notes, and snippets.

@bollwyvl
Created April 10, 2015 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bollwyvl/b34ffe2f40d64f3aae0f to your computer and use it in GitHub Desktop.
Save bollwyvl/b34ffe2f40d64f3aae0f to your computer and use it in GitHub Desktop.
d3.worker: a d3-inspired API for webworkers

d3.worker

WebWorkers are silly powerful, but also kinda clunky.

d3.worker aims to make the whole experience much nicer, by hiding some of the implementation details.

API exploration

var worker = d3.worker()
 .message("add", function(a, b){
   // this will get `toString`ed.. so no cheating!
   // `this` is the wrapped webworker... you can get at it with this.worker
   // the handlers are installed on the `message` object
   return this.message.sum(a + b);
 })
	.on("sum", function(sum){
	  // `this` is still the worker... but outside
	  return console.log("RESULT", sum);
	});

// this still feels weird...
worker();

// possible APIs
worker.message.add(1, 1);
worker.add(1, 1);

TODO

  • don't hang it off d3?
  • handle loading libraries: d3.worker().dependencies("./d3.js")
  • handle setup: d3.worker().setup(function(){})
    • does this create an initial event (i.e. ready?)
// WORK IN PROGRESS
d3.worker = function() {
var _worker = null,
_in = {all: function(){}},
_out = {
message: {all: function() {}},
error: function() {}
};
var worker = function() {
var src = "";
src = "self.addEventListener('message', function(e) {\n switch(e[0]){\n " +
src +
"\n }\n});";
var blob = new Blob([src], {type: "text/javascript"}),
url = URL.createObjectURL(blob);
_worker = new Worker(url);
_worker.onmessage = function(_arg) {
var data;
data = _arg.data;
if (data[0] in _out.message) {
return _out.message[data[0]].apply(_worker, data.slice(1));
} else {
return _out.message[all].apply(_worker, data);
}
};
return worker;
};
worker.message = function(msg, fn) {
if (_worker) {
return console.warn("Worker already created");
}
if (!msg) {
return _in;
}
switch (typeof msg) {
case "object":
return (_in = msg) && worker;
case "string":
if (fn) {
return (_in[msg] = fn) && worker;
} else {
return _in[msg];
}
}
};
worker.on = function(msg, fn) {
switch (typeof msg) {
case "object":
for(var _msg in msg){
worker[_msg] = msg[_msg];
}
return worker;
case "string":
if (fn) {
worker[msg] = fn;
return worker;
} else {
return worker[msg];
}
}
return _out;
};
worker.error = function(fn) {
if (fn) {
return (_out.error = fn) && worker;
} else {
return _out.error;
}
};
worker.post = function(data) {
_worker.postMessage(data);
return worker;
};
return worker;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment