AJAX - The Complete Reference

(avery) #1

430 Part II: Developing an Ajax Library^


var ratingImage = document.createElement("img");
ratingImage.id = ratingOptions.prefixID + (i+1);
ratingImage.onclick = function ()
{AjaxTCR.widget.ratingWidget._rateClick(this, ratingOptions);};
ratingImage.onmouseover = function ()
{AjaxTCR.widget.ratingWidget._rateOver(this, ratingOptions);};
ratingImage.src = ratingOptions.choiceOff;
ratings.appendChild(ratingImage);
}

/* set event to turn off images */
ratings.onmouseout = function ()
{AjaxTCR.widget.ratingWidget._rateOut(ratingOptions);};

/* add max range */
var maxRating = document.createElement("em");
maxRating.innerHTML = ratingOptions.maxRating;
widget.appendChild(maxRating);

/* add some line breaks */
var br1 = document.createElement("br");
widget.appendChild(br1);

var br2 = document.createElement("br");
widget.appendChild(br2);

/* create the output zone */
var ratingResult = document.createElement("div");
ratingResult.id = ratingOptions.id + "ratingResult";
ratingOptions.outputTarget = ratingOptions.id + "ratingResult";
widget.appendChild(ratingResult);
}, /* end of init() */

The rest of the code is the same so we omit it for brevity. Try it yourself at
http://ajaxref.com/ch9/ratingdegrade.html.
Separation of markup and code is really not in play here, and things are getting quite
messy. Making a simple update to the markup or style of the rating widget is going to be a
chore. We should also note that in the previous examples, we delivered fully baked HTML
fragments following the Ajah (Asynchronous JavaScript and HTML) pattern. It would
seem we should try to apply the separation of concerns we normally practice in static
HTML-CSS-JavaScript combinations or in traditional MVC (Model View Controller)
server-side applications. If we employ a client-side templating scheme, we can do just that.

Leveraging Templates


Traditionally, Web developers have attempted to decouple the markup and presentation of
pages from the programming logic and data layers. We should aim to do that as well in our Ajax
applications. It would seem then inappropriate to send a response fully styled with XHTML and
CSS. Instead, maybe only the data should be sent, likely in the form of a JSON packet.

{"average":3.37,"rating":"4","votes":475}

and then this data can be used to populate the Web page appropriately.
Free download pdf