Section 2.2. JavaScript Libraries and Prototype


2.2. JavaScript Libraries and Prototype

If you're new to Ajax, you're hopefully starting to see that doing vanilla Ajax, without the support of any extra libraries or helpers, isn't the trick it's often portrayed to be. Nonetheless, the idea of writing more than a dozen lines of code to do the simplest possible task is off-putting.

Dozens of JavaScript libraries have sprung up to make Ajax easier, and one of the most popular is Prototype, which is included with Rails. We'll cover Prototype thoroughly in Chapter 10, but for now, let's dive in with some examples. First off, let's redo the last example, this time using Prototype. Here is a new chunk to add:

<script src="/books/4/386/1/html/2//javascripts/prototype.js" type="text/javascript"> </script> <p><a href="#" onclick="prototypeAlert(  );">Call with Prototype</a></p> <script type="text/javascript">  function prototypeAlert(  ) {   new Ajax.Request('/chapter2/myresponse', { onSuccess: function(request) {    alert(request.responseText);   }})  } </script>

Note the first line, where we include the prototype.js source file so that it's usable from our page. When you first generated a new Rails app skeleton, a copy of Prototype was put in the directory public/javascripts. Inside the prototypeAlert( ) function, the first line creates a new instance of Ajax.Request, one of Prototype's classes. The first argument takes the URL to be requested, and the second argument is a JavaScript object literala collection of key/value pairs, which behaves similar to a hash or associative array in other languages. In this case, the only option given is onSuccess, which is expected to be a callback function.

Note that there's nothing in this example to handle the IE-specific versions of XMLHttpRequest and no mention of readyState codes. Prototype handles those details, leaving you with a far cleaner API.

So far, all our examples have created an alert( ) boxwhich, in your real-world applications, is probably not the most common thing you'd want to do. More often, you'll want to add or modify some content on the page. Here's a new iteration to add:

<p><a href="#" onclick="updateElement(  )">Update element </a></p> <p ></p> <script type="text/javascript">   function updateElement(  ) {     new Ajax.Request('/chapter2/myresponse', { onSuccess: function(request) {       $('response').update(request.responseText);     }})   } </script>

Note the differences from the last example: there is a new, empty paragraph element with that will hold the response we get from the server. The onSuccess function has changed, so that instead of calling alert( ), it puts the response text into the response element (using Prototype's update( ) method, which is used to set an element's innerHTML property). The dollar sign is actually the name of a function that Prototype defines, which takes a string and returns the HTML element with that ID. Since updating an HTML element will be such a common need, Prototype makes it easier, with Ajax.Updater. Check it out:

<p><a href="#" onclick="updater(  )">Update with Ajax.Updater</a></p> <p ></p> <script type="text/javascript">   function updater(  ) {     new Ajax.Updater('response2', '/chapter2/myresponse');   } </script>

Prototype's $( ) function will be used so often, it's worth looking at closely. At core, it's simply a wrapper for the standard DOM method document.getElementById, with a name that's much easier to remember and that feels like part of the JavaScript syntax. But it's more than just a wrapper. First off, it can take any number of arguments, so that you can get several elements at once. Second, every element returned is automatically extended with a powerful set of methods, detailed in Chapter 10.

Perhaps most importantly, if you pass $( ) a string, it will return the DOM element with that ID. But if you pass it any other type of objectsay, a DOM elementit simply returns the object untouched. The upshot is that you can use $( ) on a value even if you're not sure whether the value is a string or a DOM element, making your JavaScript APIs less brittle.


Note that this example doesn't have an onSuccess functionhere, Ajax.Updater just takes two arguments, the ID of the HTML element to be updated and the URL to request. Ajax.Updater requests the URL and automatically creates an onComplete function to update the specified DOM element with the responseText value. Just like Ajax.Request earlier, the last argument is a set of options. One such option is called insertion. It allows you to go beyond simply replacing the contents of an element, and instead allows you to insert content at various points. There are four insertions: Before, Top, Bottom, and After. For example:

<p><a href="#" onclick="appendToElement(  )">Append to element</a></p> <p ></p> <script type="text/javascript">   function appendToElement(  ) {     new Ajax.Updater('response3', '/chapter2/myresponse',       { insertion:Insertion.Bottom });   } </script>

When you click the link the first time, the response from the server will be added to the page, as before. On subsequent clicks, instead of being replaced, another copy of the response will be appended each time.

Notice that we've managed to reduce some fairly complex behavior into a function with just one statement. To bring this section full circle, we can reduce it back to a simple inline onclick attribute:

<p><a href="#" onclick="new Ajax.Updater('response4', '/chapter2/myresponse', { insertion:Insertion.Bottom });"> Append to element</a></p> <p ></p>

As you'll shortly see, this is exactly the sort of output that Rails' JavaScript helpers generate with ease.




Ajax on Rails
Ajax on Rails
ISBN: 0596527446
EAN: 2147483647
Year: 2006
Pages: 103
Authors: Scott Raymond

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net