|
/** |
|
* A simple class that creates another thread that responds to silly messages |
|
* with other silly messages. Okay, really it only knows 'mnah mnah' |
|
* @class Muppet |
|
* @constructor |
|
* @param Worker {Worker} injection point for Worker |
|
*/ |
|
function Muppet(Worker) { |
|
Worker = Worker || window.Worker; |
|
this.url = this.getWorkerURL(); |
|
this.worker = new Worker(this.url); |
|
} |
|
|
|
Muppet.prototype = { |
|
// get the worker script in string format. |
|
getWorkerScript: function(){ |
|
var js = ''; |
|
js += '(' + this.workerInit + ')(this);'; |
|
return js; |
|
}, |
|
|
|
// This function really represents the body of our worker script. |
|
// The global context of the worker script will be passed in. |
|
workerInit: function(global) { |
|
global.onmessage = function(e) { |
|
var response = e.data === 'mnah mnah' ? 'doot doo do-do-do' : 'huh?'; |
|
global.postMessage(response); |
|
}; |
|
global.postMessage('I am ready'); |
|
}, |
|
|
|
|
|
// get a blob url for the worker script from the worker script text |
|
getWorkerURL: function() { |
|
var blob = new Blob([this.getWorkerScript()], { type: 'text/javascript' }); |
|
return URL.createObjectURL(blob); |
|
}, |
|
|
|
|
|
// kill the muppet. Sick, just sick. |
|
kill: function() { |
|
if(this.worker) { |
|
this.worker.terminate(); |
|
} |
|
if(this.url) { |
|
URL.revokeObjectURL(this.url); |
|
} |
|
}, |
|
|
|
// say something to the muppet |
|
tell: function(msg) { |
|
if(this.worker) { |
|
this.worker.postMessage(msg); |
|
} |
|
}, |
|
|
|
// listen for the muppet to talk back |
|
says: function(handler) { |
|
if(this.worker) { |
|
this.worker.addEventListener('message', function(e) { |
|
handler(e.data); |
|
}); |
|
} |
|
}, |
|
}; |