Skip to content

Instantly share code, notes, and snippets.

@erayarslan
Created January 27, 2017 10:26
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 erayarslan/c94a3b95d18c7dd6ff9b16696bbe614f to your computer and use it in GitHub Desktop.
Save erayarslan/c94a3b95d18c7dd6ff9b16696bbe614f to your computer and use it in GitHub Desktop.
web worker lib
/*
* amele.js
* Author : Eray 'maia' Arslan
* Email : relfishere@gmail.com
* Blog : http://eray.js.org/
* This project is released under the MIT license.
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports'], function (exports) {
root.Amele = factory(root, exports);
});
} else if (typeof exports !== 'undefined') {
factory(root, exports);
} else {
root.Amele = factory(root, {});
}
}(this, function (root, Amele) {
var amele_id = 0;
Amele = function (child) {
this.id = amele_id++;
this.guid = this._guid();
this.child = child.slice(0, this._filePrefix.length) === this._filePrefix ?
new Worker(child.substr(this._filePrefix.length, child.length)) :
new Worker(URL.createObjectURL(new Blob(
[child],
{type: "text/javascript"}
)));
this._eventsUp();
return this;
};
Amele.prototype._filePrefix = "file:";
Amele.prototype.kill = function () {
this._eventsDown();
this.child.terminate();
this.child = null;
};
Amele.prototype.send = function (data) {
this.child.postMessage(data);
return this;
};
Amele.prototype.handle = function () {
};
Amele.prototype.success = function (callback) {
this.handle = callback;
return this;
};
Amele.prototype._guid = function () {
var guid = [];
for (var i = 0; i < 8; i++) {
guid.push(this._s4());
}
return guid.join("-");
};
Amele.prototype._s4 = function () {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
};
Amele.prototype._nope = function () {
};
Amele.prototype._eventsUp = function () {
var self = this;
this.child.onmessage = function (e) {
self.handle(e.data);
};
};
Amele.prototype._eventsDown = function () {
this.child.onmessage = this._nope();
};
return Amele;
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment