AJAX - The Complete Reference

(avery) #1

PART II


Chapter 5: Developing an Ajax Library 207


NNOT EOTE YUI does not require you set the Content-Type header manually to
x-www-formurlencoded for a POST, as it does this automatically. YUI does
support direct request header manipulation as discussed later in this section.

Another useful aspect of YUI is the library to address all the cross-browser event issues.
Using the Connection Manager, it is generally encouraged to use YUI’s Event utility object
that can be included using:

<script src="http://yui.yahooapis.com/2.3.0/build/event/event-min.js"></script>

This library provides a number of methods for attaching and detaching event handling
functions to objects, the most direct being the addListener() method with the following
basic syntax:

YAHOO.util.Event.addListener(object(s), event, function );

where:


  • object(s) is a DOM reference, string, or an array of strings or references to bind

    • event is a string representing the event to bind to, such as “click”



  • function is a reference to the callback function to invoke when the event is triggered


As an example:

YAHOO.util.Event.addListener("ratingForm","submit",
function () { return rate(ratingForm); } );

would bind the simple function literal shown to the submit event of the object named
ratingForm. In the following example, the function showToolTip() is bound to the
onmouseover handler of three different objects referenced in an array:

var btns = ["btn1","btn2","btn3"];
function showToolTip(e) { /* shows a tooltip */ }
YAHOO.util.Event.addListener(btns,"mouseover", showToolTip);

These various ideas are put together into a rewrite of the ever-present rating example.
This example illustrates form serialization, event binding, a failure callback with a timeout
value, and the simplicity of using POST with YUI.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Chapter 5 : YUI - Rating with POST </title>
<script src="http://yui.yahooapis.com/2.3.0/build/yahoo/yahoo-min.js"
type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.3.0/build/event/event-min.js"
type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.3.0/build/connection/connection-min.js"
Free download pdf