Popular JavaScript Framework Libraries: JQuery, the Yahoo! UI Library (YUI) and MochiKit / Page 3 | WebReference

Popular JavaScript Framework Libraries: JQuery, the Yahoo! UI Library (YUI) and MochiKit / Page 3


[prev]

Popular JavaScript Framework Libraries: JQuery, the Yahoo! UI Library (YUI) and MochiKit [con't]

Using YAHOO.lang.JSON.parse() in the Callback Success Handler

To convert the Ajax responseText into a JSON object, pass the responseText to YAHOO.lang.JSON.parse() and capture the return value. The parse() method can throw a SyntaxError exception, so be sure to wrap the call in a try/catch block:

UI Controls

Perhaps the most impressive part of the YUI Framework is the collection of configurable control/widgets. Not only are they extremely versatile and useable, but they can also be given a cohesive, visual look and feel, using skins. The skin, which is the visual presentation of YUI controls, is defined with CSS. It's named "Sam" after their creator Sam Lind.

Ironically, the Autocomplete control that I used as a prototype to my own control in my Creating an Autocomplete Control series, is available through the YUI:

Image 1

Other controls include Button, Calendar, Carousel, Color Picker, Container (including Module, Overlay, Panel, Tooltip, Dialog, SimpleDialog), DataTable, ImageCropper, Layout Manager, Menu, Paginator, Rich Text Editor, Slider, TabView and TreeView. Some newer ones are still in the beta or experimental phase, but they'll soon be in a bug-free and reliable state.

CSS Components

The CSS components' purpose is to neutralize the inconsistent default browser handling of CSS properties, creating a level playing field across major browsers and providing a sound foundation for development. There are four CSS components: CSS Reset, CSS Base, CSS Fonts and CSS Grids.

  • CSS Reset: removes the default styling of HTML elements, so that styles are applied consistently.
  • CSS Base: takes over where CSS Reset ends, by applying a consistent style foundation for common HTML elements across major browsers.
  • YUI Fonts: offers cross-browser typographical normalization and control.
  • YUI Grids: includes over 1000 page layout combinations in a 4kb file, including four preset page widths, six preset templates, and the ability to stack and nest subdivided regions of two, three, or four columns.

Developer Tools

A big plus to using the YUI Framework is the access to the developer tools. These components help you to debug and unit test your pages - usually not an easy task with JavaScript. Components include a Logger Control, Profiler, which provides client-side, cross-browser profiling, the beta version of the ProfilerViewer Control and the YUI Test Utility.

The Logger Control provides a simple way to read or write log messages. It allows you to tap into the rich event-driven messages included with the YUI Library's debug files. A simple messaging interface allows you to filter, pause, resume and clear log messages on your screen. Alternatively, you can monitor log output via the FireBug extension for Firefox or via the Safari JavaScript console. The Logger is extendable, allowing developers to build their own implementations to suit advanced requirements.

The YUI Profiler is a simple, non-visual code profiler for JavaScript. Unlike most code profilers, this one allows you to specify exactly what parts of your application to profile. You can also programmatically retrieve profiling information as the application is running, allowing you to create performance tests YUI Test or other unit testing frameworks.

YUI's Profiler is a GUI add-on to the Profiler which generates profiling data about the JavaScript functions that comprise your Web application. The ProfilerViewer Control is used in combination with Profiler to provide rich visualizations of your profiling data - both graphically (using the Charts Control) and in tabular format (using DataTable).

YUI Test is a testing framework for browser-based JavaScript solutions. Using YUI Test, you can easily add unit testing to your JavaScript solutions. While not a direct port from any specific xUnit framework, YUI Test does derive some characteristics from nUnit and JUnit. The basis of YUI Test is the YAHOO.tool.TestCase object. A TestCase object is created by using the YAHOO.tool.TestCase constructor and passing in an object containing methods and other information with which to initialize the test case. Typically, the argument is an object literal:

The YUI Compressor

After design optimization, the next best strategy for improving performance is minification of the code, using techniques such as HTTP compression and CSS sprites. That's where the YUI compressor comes in. As noted above, the YUI Framework isn't the least verbose of the crop. Therefore, compressing the JavaScript and CSS files helps to overcome potential performance degradation. The goal of JavaScript and CSS minification is to preserve the operational qualities of the code while reducing its overall byte footprint. The YUI Compressor is designed to be 100% safe and yield a higher compression ratio than most other tools. Tests on the YUI Library have shown savings of over 20% compared to JSMin (becoming 10% after HTTP compression).

MochiKit

According to their Web site, "MochiKit makes JavaScript suck a bit less"! They must be right, because MochiKit is the fifth most popular JavaScript Framework in use today. The designers of the Mochikit Framework borrowed from Python and Objective-C and adapted it to the world of JavaScript. Perhaps as a result of the author Bob Ippolito's involvement in the Python community, MochiKit forms the foundation of the client-side functionality of the TurboGears Python Web-application stack. Its similarities to the Python language have made it a favorite among Python-based Web applications.

MochiKit has a lot going for it. For starters, its designers are test and documentation obsessed. Both those traits can be hard to come by in the JavaScript world! MochiKit doesn't mess with the Object.prototype, and inserts just three symbols into the global namespace: the MochiKit namespace, plus the compare() and reduce() functions to work around JScript bugs. JSAN and Dojo Toolkit are fully supported by and interoperable with MochiKit!

MochiKit contains algorithms for data structures (including serialization), functional programming, iteration, DOM and CSS manipulation, asynchronous server communication, JavaScript events and logging tools. MochiKit also provides functionality for drag and drop, colors and visual effects.

Event Support

MochiKit provides a couple of ways to add event handlers to document events. The easiest is to use the MochiKit.DOM.addLoadEvent() function. In the following example, the addLoadEvent() function is used to call the MochiKit.Visual.roundClass() function to give all tables rounded corners and to round only the top corners on the element with the ID of "roundedParagraph":

Another way to associate a function with a particular event is to use the MochiKit.Signal.connect() function. For instance, MochiKit.Signal.connect(window, "onload", myOnLoadFunction); would call myOnLoadFunction() during the window.onload event. Let's use the MochiKit.Base.map(), MochiKit.Base.partial(), MochiKit.Signal and MochiKit.DOM to create a link that can be clicked only once and then goes away:

When the document loads in the browser, myOnLoadFunction() is called. It gathers all the <A> elements whose class is 'oneclick' and passes them, one by one, to the connectOneClickOnly() function, using the MochiKit.Base.map() function. It takes an array of objects and applies a function to them. The connectOneClickOnly() function creates a new handler for the links by passing our makeNewObj() function to the MochiKit.Base.partial() function, which is short for "partial function application." We supply a function as the parameter, which creates the replacement <SPAN> element, to our event handler callback. The MochiKit.Signal class will call our function when the user clicks on a on a link:

To create our new <SPAN> tag, we can use one of MochiKit's many common tag functions. These are a shortcut to calling the createDOM() function:

Normally, the event handler would would only accept the eventObj parameter passed by MochiKit.Signal, but since we applied the MochiKit.Base.partial() to it earlier, the makeNewObj() function (called fnMakeNew() locally) is passed as the first parameter:

The swapDOM() function of the MochiKit.DOM package is used to replace the link with the new <SPAN> node.

Ajax

All asynchronous function calls in the MochiKit are done via the Deferred class. It's easy to see how in the context of a Web browser an XMLHttpRequest to a server would qualify as a Deferred object. Nonetheless, the Deferred object encompasses far more than Ajax calls, since it provides a consistent API for all asynchronous computations that occur exactly once. The Deferred object is capable of managing very complex tasks such as cancellation and callback chains.

Most of the time, you won't even know that the Deferred class is there, because MochiKit's convenience functions create the object behind the scenes. For example, a GET Ajax call can be performed using the MochiKit.Async.doSimpleXMLHttpRequest() function. It accepts two arguments: the URL to send the request to, and a JSON object containing name/value pairs. Unlike other Frameworks, like Prototype, MochiKit doesn't include the callback functions in the arguments list, but requires that you call two additional functions called addCallback(function) and addErrBack(function). HTTP codes of 200 (OK), 201 (CREATED), 204 (NO CONTENT) and 304 (NOT MODIFIED) are considered success codes. All other status codes will result in an Errback with an XMLHttpRequestError object:

Next week, we'll continue our overview of popular JavaScript Frameworks with the Dojo, Rialto and Spry Frameworks.

Original: October 24, 2008


[prev]