HTML and CSS Reference
In-Depth Information
parameter to pass to the worker thread. Hence, these pieces of data are grouped in a JSON object with
three properties:
CustomerID
,
StartDate
, and
EndDate
.
To begin processing, the
Worker
object's
postMessage()
method is invoked and the JSON
settings
object is passed to it as a parameter.
Event Handlers for message and error Events
The
ReceiveDataFromWorker()
event-handler function receives the order data returned by the worker
thread. This function is shown in Listing 10-10.
Listing 10-10.
Receiving and Displaying Order Details
function ReceiveDataFromWorker(evt) {
var data = evt.data;
$("#orderTable").empty();
$("#orderTable").append("<tr><th>Order ID</th><th>Customer ID</th>
<th>Order Date</th><th>Order Amount</th></tr>");
for (var i = 0; i < data.length; i++) {
$("#orderTable").append("<tr>" +
"<td>" + data[i].OrderID + "</td>" +
"<td>" + data[i].CustomerID + "</td>" +
"<td>" + ToJSDate(data[i].OrderDate) + "</td>" +
"<td>" + data[i].OrderAmount + "</td>" +
"</tr>");
}
$("#getOrders").removeAttr("disabled");
$("#getOrders").val("Get Orders");
}
ReceiveDataFromWorker()
receives order data from the worker thread as an array. Each element of the
array represents an order and has properties:
OrderID
,
CustomerID
,
OrderDate
, and
OrderAmount
. The
evt.
data
property gives you access to this array.
The
orderTable
HTML table is emptied to remove any previously added rows. A
for
loop iterates
through the JSON collection. With every iteration, a row is added to the table and the
OrderID
,
CustomerID
,
OrderDate
, and
OrderAmount
property values are displayed.
Notice that unlike
OrderID
and
CustomerID
,
OrderDate
isn't directly displayed in the table. The
OrderDate
value is first passed to a helper function—
ToJSDate()
—and the return value of
ToJSDate()
is
displayed in the table. The
OrderDate
column is a date-time column in the database, but the JSON format
doesn't have a date data type. So, when dates are serialized from the server to the client, they're sent in a
special format. For example, if
OrderDate
is
8/12/1996
(mm/dd/yyyy) in the database, the JSON equivalent
is
/Date(839788200000)/
. The number in
Date()
is the number of milliseconds between that date and
midnight of 1 January 1970. The
ToJSDate()
helper function converts this cryptic-looking value into a
readable form.
ToJSDate()
is shown in Listing 10-11.
Listing 10-11.
Converting a JSON Date Value into a JavaScript Date
function ToJSDate(value) {
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}