HTML and CSS Reference
In-Depth Information
The evt.data property returns the processing result sent by the worker thread. The actual processing
( do - while loop) now resides in the Processing.js script file (see Listing 10-3).
Listing 10-3. Code Running in a Worker Thread
addEventListener("message", ReceiveMessageFromPage, false);
function ReceiveMessageFromPage(evt) {
var date = new Date();
var currentDate = null;
do {
currentDate = new Date();
}
while (currentDate - date < 10000);
postMessage("Page said : " + evt.data + "\r\n Worker Replied : Hello Page!" );
}
Earlier, you wired the web page's message event handler to receive the message sent by the worker
thread. Along the same lines, you need to wire the message event handler for the Worker to receive the
message sent by the web form. The addEventHandler() call in Listing 10-3 does that job. The message event
for the worker thread is raised when the web form calls the postMessage() method on the Worker object. In
this case, the Worker 's message event is handled by the ReceiveMessageFromPage() function.
ReceiveMessageFromPage() contains the same do - while loop as before. Notice, however, that there are
no alert() calls because the worker thread can't have user interactions. Once the do - while loop completes,
the worker thread calls postMessage() to send the processing result back to the web form. Notice how the
data sent by the web form (“Hello Worker!”) is retrieved in ReceiveMessageFromPage() using the evt.data
property.
Figure 10-2 shows a sample run of the web form.
Figure 10-2. Processing.js running in a worker thread
The web form passes the string “Hello Worker!” to the worker thread. The worker thread forms a string
by prefixing the evt.data value with “Page said :” and suffixing “Worker Replied : Hello Page!”. The string is
then returned to the web form. The ReceiveMessageFromWorker() function written in the web form displays
the return value in an alert() box. Using the web worker object, the UI isn't blocked when you click the
Start Work button. You can interact with the page freely because the processing is taking place in the
background. When the processing is finished, you're notified and the result of the processing is displayed.
To make the interaction between the web form and the worker thread clear, Figure 10-3 displays the
working of this application in pictorial form.
 
Search WWH ::




Custom Search