Skip to content

Instantly share code, notes, and snippets.

@wryk
Created September 8, 2014 13:27
Show Gist options
  • Select an option

  • Save wryk/eede931745b43da31b44 to your computer and use it in GitHub Desktop.

Select an option

Save wryk/eede931745b43da31b44 to your computer and use it in GitHub Desktop.
wryk/function-worker
import inherit from 'inherit';
export default CallbackWorker;
var inherit = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
var properties = {
type: 'application/javascript'
};
inherit(CallbackWorker, Worker);
function CallbackWorker (fn) {
var blob = new Blob(['(' + fn + ')();'], properties);
this._objectURL = URL.createObjectURL(blob);
this._worker = new Worker(this._objectURL);
this._worker.onmessage = function (event) {
this.dispatchEvent(new event.constructor(event.type, event));
};
}
CallbackWorker.prototype.postMessage = function () {
this._worker.postMessage.apply(this._worker, arguments);
};
CallbackWorker.prototype.terminate = function () {
this._worker.terminate();
URL.revokeObjectURL(this._objectURL);
};
worker = new CallbackWorker(function () {
self.onmessage = function (event) {
self.postMessage(event.data + ' !');
};
});
worker.onmessage = function (event) {
console.log('got : ' + event.data); //should be 'hello !'
};
worker.postMessage('hello');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment