};
this.postMessage = function (vMsg) {
//I just think there is no need to use call() method
//how about just oWorker.postMessage(vMsg);
//the same situation with terminate
//well,just a little faster,no search up the prototye chain
Worker.prototype.postMessage.call(oWorker, vMsg);
};
this.terminate = function () {
Worker.prototype.terminate.call(oWorker);
};
this.addListener = function (sName, fListener) {
oListeners[sName] = fListener;
};
this.removeListener = function (sName) {
delete oListeners[sName];
};
};
// your custom "queryable" worker
var oMyTask = new QueryableWorker("my_task.js" /* , yourDefaultMessageListenerHere [optional], yourErrorListenerHere [optional] */);
// your custom "listeners"
oMyTask.addListener("printSomething", function (nResult) {
document.getElementById("firstLink").parentNode.appendChild(document.createTextNode(" The difference is " + nResult + "!"));
});
oMyTask.addListener("alertSomething", function (nDeltaT, sUnit) {
alert("Worker waited for " + nDeltaT + " " + sUnit + " :-)");
});
</script>
</head>
<body>
<ul>
<li><a id="firstLink" href="javascript:oMyTask.sendQuery('getDifference', 5, 3);">What is the difference between 5 and 3?</a></li>
<li><a href="javascript:oMyTask.sendQuery('waitSomething');">Wait 3 seconds</a></li>
<li><a href="javascript:oMyTask.terminate();">terminate() the Worker</a></li>
</ul>
</body>
</html>
my_task.js (the worker):
// your custom PRIVATE functions
function myPrivateFunc1 () {
// do something
}
function myPrivateFunc2 () {
// do something
}
// etc. etc.
// your custom PUBLIC functions (i.e. queryable from the main page)
var queryableFunctions = {
// example #1: get the difference between two numbers:
getDifference: function (nMinuend, nSubtrahend) {
reply("printSomething", nMinuend - nSubtrahend);
},
// example #2: wait three seconds
waitSomething: function () {
setTimeout(function() { reply("alertSomething", 3, "seconds"); }, 3000);
}
};
// system functions
function defaultQuery (vMsg) {
// your default PUBLIC function executed only when main page calls the queryableWorker.postMessage() method directly
// do something
}
function reply (/* listener name, argument to pass 1, argument to pass 2, etc. etc */) {
if (arguments.length < 1) { throw new TypeError("reply - not enough arguments"); return; }
postMessage({ "vo42t30": arguments[0], "rnb93qh": Array.prototype.slice.call(arguments, 1) });
}
onmessage = function (oEvent) {









