11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

pcResult = true;<br />

If you enter a misspelled word, for example, ―absquatalate,‖ the server should return the<br />

corrected spelling:<br />

rpc<strong>Complete</strong> = true;<br />

rpcResult = "absquatulate";<br />

This example is shown in action in Figure 19-2.<br />

Figure 19-2: Spellchecking using RPC<br />

One aspect of the previous script is particularly noteworthy: If we want to send an RPC request<br />

while one is already pending, we must wait for the first request to complete. Once the browser<br />

has begun loading the first RPC‘s , we can‘t stop it, and if we start another RPC<br />

while it‘s loading we run the risk of clobbering the return values. <strong>The</strong>re are ways around this<br />

problem. For example, you can keep arrays of timers and return values in order to manage<br />

multiple requests concurrently. Another, more elegant approach is to use a callback.<br />

Callbacks<br />

A callback is a function that will be called when an RPC completes. <strong>The</strong> idea is simple: instead<br />

of periodically checking whether an RPC has completed, have the script returned by the server<br />

call a function instead.<br />

Using a callback simplifies our spelling correction script:<br />

<br />

var commandURL = "http://demos.javascriptref.com/checkspelling.php?";<br />

// Sends the RPC given in url. <strong>The</strong> server will return <strong>JavaScript</strong> that<br />

calls<br />

// RPC<strong>Complete</strong>() with the result.<br />

function sendRPC(url)<br />

{

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!