Created
May 23, 2014 12:18
-
-
Save AlexMocioi/3cbb00b82b96b7e87591 to your computer and use it in GitHub Desktop.
Abstracting The Web Worker: Operative
http://james.padolsey.com/javascript/abstracting-the-web-worker-operative/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
HTML5 Web Workers are the web’s answer to multi-threading. They’ve been around for a while now, so are pretty safe to rely on. A Worker is typically initialised by instantiating Worker with the URL of your ‘worker script’: | |
*/ | |
var myWorker = new Worker('path/to/my/worker.js'); | |
/* | |
And then you’d interface with the worker via asynchronous message-passing: | |
*/ | |
// == Within parent page == | |
myWorker.postMessage('Did you receive this?'); | |
myWorker.onmessage = function() { | |
if (e.data === 'I sure did, friend.') { | |
myWorker.postMessage('Cool, I am gonna send you some data, k?'); | |
} | |
// etc. | |
} | |
// == Within worker == | |
self.onmessage = function(e) { | |
if (e.data === 'Did you receive this?') { | |
self.postMessage('I sure did, friend.'); | |
} | |
// etc. | |
}; | |
/* | |
The message-passing code I tend to see in the wild is typically un-abstracted and chaotic. I felt there was some things worth improving in this area so I created operative. | |
Operative allows you to define worker code inline without having to create specific files and load them separately at runtime. With operative it’s as simple as: | |
*/ | |
var calculator = operative({ | |
// Any methods defined here are executed within a worker! | |
doComplexThing: function(a, b, c) { | |
// do stuff. | |
return result; | |
} | |
}); | |
// Call method, passing a callback as the last arg: | |
calculator.doComplexThing(1, 2, 3, function(result) { | |
result; // => value returned from within worker | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment