ajsfw
Version:
Ajs Framework
113 lines (112 loc) • 4.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var ajsWorkerInstance = null;
var AjsWebWorker = (function () {
function AjsWebWorker(worker) {
var _this = this;
this.__initialized = false;
this.__initState = 0;
this.__worker = worker;
this.__transportRecievers = {};
this.__worker.onmessage = function (e) {
_this.__onMessage(e);
};
}
AjsWebWorker.prototype.registerReceiver = function (protocol, reciever) {
if (!(protocol in this.__transportRecievers)) {
this.__transportRecievers[protocol] = [];
}
this.__transportRecievers[protocol].push(reciever);
};
AjsWebWorker.prototype.send = function (protocol, data) {
var message = {
protocol: protocol,
data: data
};
this.__worker.postMessage(message);
};
AjsWebWorker.prototype.__onMessage = function (e) {
if (!this.__initialized) {
this.__initialize(e.data);
return;
}
;
if (e.data.protocol === undefined || e.data.data === undefined) {
throw new Error("Invalid message transport protocol");
}
if (e.data.protocol in this.__transportRecievers) {
for (var _i = 0, _a = this.__transportRecievers[e.data.protocol]; _i < _a.length; _i++) {
var reciever = _a[_i];
reciever(this, e.data.data);
}
}
};
AjsWebWorker.prototype.__initialize = function (data) {
var _this = this;
switch (this.__initState) {
case 0:
this.__loadLibraries(data, function () {
_this.__worker.postMessage("librariesLoaded");
_this.__initState++;
});
break;
case 1:
var startWorkerCode = this.__runCode(data);
this.__worker.postMessage("initDone");
this.__initialized = true;
startWorkerCode();
break;
default:
throw new Error("Invalid Ajs Web Worker init state");
}
};
AjsWebWorker.prototype.__loadLibraries = function (libraries, doneCb) {
var _this = this;
var loadedLibraries = {};
var loadedCount = 0;
for (var _i = 0, libraries_1 = libraries; _i < libraries_1.length; _i++) {
var l = libraries_1[_i];
loadedLibraries[l] = null;
this.__loadLibrary(l, function (url, code) {
loadedLibraries[url] = code;
loadedCount++;
if (loadedCount === libraries.length) {
for (var _i = 0, libraries_2 = libraries; _i < libraries_2.length; _i++) {
var lib = libraries_2[_i];
_this.__runCode.call(_this.__worker, loadedLibraries[lib]);
}
doneCb();
}
});
}
};
AjsWebWorker.prototype.__runCode = function (code) {
return eval.call(this, code);
};
AjsWebWorker.prototype.__loadLibrary = function (url, doneCb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function (e) {
if (xhr.readyState === xhr.DONE) {
doneCb(url, xhr.responseText);
}
};
xhr.onerror = function (e) {
console.error("Failed to load library " + url, e);
};
xhr.onabort = function (e) {
console.error("Failed to load library " + url, e);
};
xhr.send();
};
return AjsWebWorker;
}());
function run() {
if (this.hasOwnProperty("document")) {
this.document.write("Web worker script can't be started in the main thread!");
}
else {
ajsWorkerInstance = new AjsWebWorker(this);
}
}
exports.run = run;