Last active
May 25, 2016 01:03
-
-
Save preco21/5a8e152070d1054b4f00 to your computer and use it in GitHub Desktop.
Simple InlineWorker
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
import Promise from 'bluebird'; | |
import EventEmitter from 'eventemitter3'; | |
class InlineWorker { | |
constructor(source) { | |
if (typeof source != 'function') { | |
throw new TypeError('source must be a function'); | |
} | |
if (this._worker) { | |
this.terminate(); | |
} | |
let methodString = source.toString().trim().match(/{([\w\W]*?)}/)[1]; | |
this._createWorker(methodString); | |
this._worker.addEventListener('message', (event) => this._messageHandler(event)); | |
this._worker.addEventListener('error', (error) => this._errorHandler(error)); | |
} | |
start(data) { | |
if (!this._worker) { | |
throw new Error('Worker is not created'); | |
} | |
return new Promise((resolve, reject) => { | |
this._worker.postMessage(data); | |
this.once('message', resolve); | |
this.once('error', reject); | |
}); | |
} | |
terminate() { | |
if (!this._worker) { | |
throw new Error('Worker is not created'); | |
} | |
this._worker.terminate(); | |
this._worker = null; | |
URL.revokeObjectURL(this._workerBlob); | |
this._workerBlob = null; | |
} | |
_createBlobURL(source) { | |
let blob = new Blob([source]); | |
return URL.createObjectURL(blob); | |
} | |
_createWorker(blobURL) { | |
this._workerBlob = this._createBlobURL(blobURL) | |
this._worker = new Worker(this._workerBlob); | |
} | |
_errorHandler(error) { | |
this.emit('error', new Error(`${error.message} (${error.filename}:${error.lineno})`)); | |
} | |
_messageHandler(event) { | |
this.emit('message', event.data); | |
} | |
} | |
mixinEventEmitter(InlineWorker); | |
function mixinEventEmitter(target) { | |
Object.assign(target.prototype, EventEmitter.prototype); | |
target.prototype.constructor = target; | |
} | |
export { | |
InlineWorker as default | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: