HTML and CSS Reference
In-Depth Information
In the preceding code block, you can see we're accessing the
worker via the port property. This is how you interact and, in
fact, distinguish between shared and nonshared workers. As the
example binds to the message event using addEventListener ,
the worker must be connected manually using the .start()
method. The code wouldn't need this if it used onmessage .
Next is the messages.js worker:
var connections = [];
onconnect = function(event) {
var xhr = new XHR('/get-new-messages');
xhr.oncomplete = function (messages) {
for (var i = 0; i < connections.length; i++) {
xhr.send(); // causes us to loop forever
When a client document connects to the worker, the connect
event is fired, which allows me to capture the connection port.
This is collected through the event.ports[0] reference, even
though there will never be more than one item inside the ports
property. However, the worker reference is inside this, so we
can use this to post messages and receive messages.
As you see in the previous example, when the Ajax oncomplete
function runs, I loop through all the connected ports and send
them each a message of the new email messages that have
come in. This way the connected clients act as dumb terminals,
oblivious to any of the real work going on to store the messages
in the client-side database.
Search WWH ::

Custom Search