-
Notifications
You must be signed in to change notification settings - Fork 0
/
knowledge-worker.js
57 lines (50 loc) · 1.44 KB
/
knowledge-worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
KnowledgeWorker = (function() {
var sentinel_name = "KnowledgeWorker sentinel value";
var sentinel_value = 8675309;
function is_sentinel(data) {
return data.constructor === Object && data[sentinel_name] === sentinel_value;
}
return function KnowledgeWorker(script) {
var knowledgeWorker = this;
var worker = new Worker(script);
var default_behavior = true;
this.postMessage = function postMessage(message) {
worker.postMessage.apply(worker, Array.prototype.slice.call(arguments, 0));
};
this.terminate = function terminate() {
worker.terminate.apply(worker, Array.prototype.slice.call(arguments, 0));
}
function default_onmessage(e) {
if (is_sentinel(e.data)) {
default_behavior = false;
} else {
if (knowledgeWorker.onmessage) {
knowledgeWorker.onmessage(e);
}
}
}
function kw_onmessage(e) {
if (e.data["command"]) {
var consoleMatches = /console\.([^.]*)/.exec(e.data.command);
if (consoleMatches) {
var method = consoleMatches[1];
console[method].apply(console, e.data.arguments);
} else if (e.data.command === "message") {
if (knowledgeWorker.onmessage) {
knowledgeWorker.onmessage({"data": e.data.data});
}
}
} else {
console.error(e.data);
throw new Error("malformed KnowledgeWorker message");
}
}
worker.onmessage = function(e) {
if (default_behavior) {
default_onmessage(e);
} else {
kw_onmessage(e);
}
}
};
})();