Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created February 15, 2011 22:34
Show Gist options
  • Save rwaldron/828410 to your computer and use it in GitHub Desktop.
Save rwaldron/828410 to your computer and use it in GitHub Desktop.
self calling worker
document.addEventListener( "DOMContentLoaded", function() {
var selfy = selfish();
selfy.worker.addEventListener( "message", function( event ) {
var data = event.data;
console.log( data );
});
selfy.worker.postMessage({
renderer: "the renderer sent this"
});
}, false);
<!DOCTYPE html>
<html>
<head>
<title>Self.js</title>
<script src="self.js"></script>
<script src="self-demo.js"></script>
</head>
<body>
</body>
</html>
(function( global ) {
function Selfish() {
// create a worker for this instance
this.worker = new Worker( "self.js" );
// return the worker
return this;
}
// Create Instances without new'ing them
function selfish() {
return new Selfish();
}
// Expose to global scope
global.selfish = selfish;
})( this );
// WorkerGlobalScope //
// We can safely attach this to the
// window/global scope using onmessage;
onmessage = function( event ) {
var data = event.data;
data.worker = "The worker saw this message and is replying to the renderer";
// boring, but you get the idea...
self.postMessage( data );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment