Created
September 8, 2014 13:27
-
-
Save wryk/eede931745b43da31b44 to your computer and use it in GitHub Desktop.
wryk/function-worker
This file contains hidden or 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
| 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); | |
| }; |
This file contains hidden or 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
| 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