Article

The JavaScript Library World Cup

Page: 1 2

1537_mochikit

Mochikit

Mochikit is the brain child of Bob Ippolito (the primary contributor) and is available from the Mochikit site. The basic package weighs in at around 90KB (compressed), but you can load each of the modules separately. Mochikit is also currently bundled with the Python web framework, TurboGears.

In the words of Bob,

We took all the good ideas we could find from our Python, Objective-C, etc. experience and adapted it to the crazy world of JavaScript.


So, to a large extent, Mochikit draws on the idioms of Python for its API. If you're familiar with Python, you'll have an instant head start with Mochikit, although it has a simple API which is reasonably easy to pick up. Of all the libraries covered in this article, Mochikit's API feels the most "designed". Rather than relying on package-style naming conventions, it exports a select number of functions to the global namespace, which helps make your scripts a lot more compact.

When getting started with Mochikit, you should:

  1. Watch Bob's screencast.

  2. Start bashing away using Mochikit's excellent interactive interpreter, much like you would with Python. This is a great way to get a feel for the library and a basic understanding of how Mochikit works.

The Basics

When working with the DOM, Mochikit has some real tricks up its sleeve:

var warning = P(  
 { 'class' : 'warning' },  
 "Please provide a ", STRONG(null, "valid email address")  
);  
swapDOM(document.getElementById("notifications"), warning);

This code will use the relevant W3C DOM methods to create the equivalent node tree for the following HTML:

<p class="warning">Please provide a <strong>valid email address</strong></p>

The Mochikit code is almost cleaner than the HTML syntax!

The Mochikit.DOM module also contains a number of other methods for easy DOM manipulation, such as the swapDOM method mentioned above (which does what it says on the tin), and toHTML (which converts a DOM node to the HTML it represents). And just for good measure, Mochikit has thrown in the $ function for those who are used to it.

As far as event handling goes, Mochikit has a well designed (if slightly unfamiliar system) that's implemented in the Mochikit.Signal module. It's based around the concept of connecting a listener to a signal that's sent from an object. All the regular DOM events are signals, but you can create your own, too. The connect method does all the work here:

// connects the onclick signal of the element with id="thing"  
// to the function showDialog, which points to the element.  
connect($('thing'), 'onclick', showDialog);  
 
// connects the onsubmit signal of element id="form" to  
// formController.checkSubmit, which points to the  
// formController object.  
connect($('form'), 'onsubmit', formController, 'checkSubmit');

You can make your own objects send signals simply with the signal method:

signal(anObject, 'a_signal');

While Mochikit's event system is a departure from the way you might normally expect event handling to work, it's actually brutally simple and great to use once you get used to it.

AJAX stuff is handled by the Mochit.Async module, and the Deferred objects which lie at the core of the implementation. To perform a basic AJAX call, use either loadJSONDoc or doSimpleXMLHttpRequest:

var request = doSimpleXMLHttpRequest('get_options.php',  
   { q : 'web developer'}  
);

This function returns a Deferred object, on which you can set callbacks:

request.addCallbacks(mySuccessFunction, myErrorFunction);

When the XMLHttpRequest is complete, the relevant callback is called and passed the XMLHttpRequest object as the argument:

function mySuccessFunction(req) {  
 alert(req.responseText);  
}

Deferred objects are useful for any asynchronous programming and are a great idea. Read more here, or watch the screencast for more details.

Highs and Lows

First off, Mochikit's logging framework is excellent. Simply add logging statements:

log("This is so much better than alert");  
log("ERROR This thing is broke");

You can then use Mochikit's bookmarklet to open a log window and view your log messages. You don't need to add anything into your pages or include any extra script -- it's truly effortless and beats alert any day.

Mochikit also makes full use of JavaScript's functional programming features to really enhance and simplify the library's API. For instance, if you want to sort a group of objects by their name properties, you can use keyComparator to create the sort function for you:

var sortedByName = people.sort(keyComparator("name"));

There's also the useful counter function. This creates a function which returns a value that's incremented by one every time it's called:

var nextId = counter();  
nextId(); //=> 1  
nextId(); //=> 2  
nextId(); //=> 3

There's also a full set of Python-style iteration functions, such as forEach, map and filter, which are sure to see heavy use.

As far as documentation goes, Mochikit has some very good API documentation, but details on some very basic parts of the library are a little lacking. In particular, after reading all the docs, watching the screencast and writing a few Mochikit-based scripts, I'm still unsure which version of the library is best suited for any purpose. Do I use the packed version or the main Mochikit.js? How can I load individual parts of the library?
However, Mochikit does have a mailing list, so answers to these kinds of questions are, no doubt, not far away. All in all, Mochikit may not be what you're used to in terms of a JavaScript library, but it's beautifully designed and I'm looking forward to seeing where Bob takes it.

1537_yui

Yahoo! UI Library

The Yahoo! UI Library or (YUI as it's commonly been referred to) was developed by Yahoo! for internal use, but has recently been open sourced along with a whole raft of excellent developer resources at developer.yahoo.com.

YUI is more a distinct set of "utilities" than a coherent library, with five core scripts that cover:

  • animation
  • AJAX
  • DOM manipulation
  • drag-and-drop
  • event handling

And there are six controls, namely:

  • Calendar
  • Slider
  • Menu
  • AutoComplete
  • Tree View
  • Container classes (with which you can implement all manner of window-style widgets)

You can download each of these scripts individually from the developer.yahoo.com site.

There is a definite advantage to this loosely coupled approach to designing libraries -- it often seems a bit of an overkill to have users download 100 or so kilobytes of library when, for instance, they only want to use the event system.

Each of the Yahoo! libraries depends only on the small yahoo.js file. On the other hand, this approach offers a slightly less coherent experience for the developer and could possibly introduce a certain amount of repetition within the libraries.

One thing that feels awkward about YUI is the fact that it's very heavily namespaced. Every call you make to the library needs to be prefixed with a hefty package string:

var myAnim = new YAHOO.util.Anim(  
 'test',  
 { height: {to: 10} },  
 1,  
 YAHOO.util.Easing.easeOut  
);  
myAnim.animate();

This all seems rather verbose, and I'm unsure whether JavaScript really requires that degree of namespacing -- usually we'd never have that much code loaded into any one page. Nevertheless, YUI is a straightforward and utilitarian library with a primary focus that seems to be smoothing over browser differences as simply as possible.

The Basics

YUI's event handling library should have a very familiar API for those who are used to the native browser event handling methods. However, it packs a few nice surprises that Yahoo! developer, Dustin Diaz, has explained in some detail on his site. You can set a simple listener like this:

YAHOO.util.event.addListener('object_id', 'click', callBackFunction);

A very powerful feature of the event library is its deferred attachment of event listeners. Essentially, if you attempt to attach a listener to an element that does not yet exist because the page hasn't loaded yet, it will transparently wait for that page to become available before attaching to the event. This is a neat solution to an issue that has confused and frustrated many DHTML newbies.
The DOM library abstracts over browser inconsistencies, allowing the seamless setting of styles and reporting of element properties. However, while it takes care of the common tasks reasonably well, there are a few surprises in here:

  • get is YUI's version of the infamous $ function.
  • One interesting method is generateId, which can be used to generate IDs for elements programmatically so you can quickly access them at other points in the script. It's not immediately obvious why this approach would be used over simply storing references to the objects, though, so I'd be interested to see it used in a real script.

The Connection Manager contains all of YUI's AJAX magic, and in line with the other libraries, chooses not to take a high-level approach. It does nothing more than provide a cross browser interface to XMLHttpRequest:

YAHOO.util.Connect.asyncRequest(  
 'GET',  
 'http://www.yahoo.com',  
 callback  
);

One highlight is the rich callback interface, which allows you to define an object that wraps your callback functions as well as some extra configuration. Here's an example callback object:

var callback = {  
 success: function(resp) { alert('WOO!!'); }, // called on success  
 failure: function(resp) { alert('BOO!'); }, // called on error  
 argument: arguments, // user defined arguments  
 scope: formController // scope the callbacks are called within  
}

Highs and Lows

The documentation provided by Yahoo! for the library is excellent. The site has formal API documentation, plenty of examples, a mailing list and some brief but clear explanations of the main features of each part of the library. However, as with Dojo and Mochikit, the library has not quite managed to capture the imagination of the developer community as much as Prototype, so independent articles are still thin on the ground at the moment. The best place to check for articles about YUI is Yahoo! developer, Dustin Diaz's site.

As I implied above, the event handling implementation is one of YUI's main strengths, and the fact that it is decoupled from the other parts of the library means that it could well see a lot of use independently from the rest of the library. However, the rest of the library, while being very functional, doesn't contain as many innovative features as the likes of Mochikit, Dojo and Prototype, and because of the long package strings, coding with YUI sometimes feel rather long-winded.

Yet the growing list of components is very rich. For instance, the Calendar component supports several languages and multiple date selections, and the Container classes give you the power to implement all kinds of windowed interfaces. One downside of using these components is that they tend to be very heavily dependent on the other libraries; in discussing this, Dean Edwards highlights as an example the treeview control, which uses around 260K of JavaScript.

Which one Wins?

Well, the short answer to this question is that there is no real stand-out solution that excels in all situations.

Prototype is the most comprehensively documented -- albeit in a splintered way. It is also seemingly the most widespread library at the moment, possibly because it really excels at the kind of tasks developers complete most often, like selecting nodes and working with lists. Of course, it's going to be the natural choice for Ruby developers because it sticks to many Ruby idioms. One other great thing about Prototype is that it has the mighty weight of Rails behind it and, as a result, there are many developers providing bug fixes and patches to Prototype. Finally, it offers a wealth of add-on libraries such as scriptaculous, Rico, and Behaviour that make it a good, solid choice for many developers.

On the other hand, Prototype has a very under-developed event handling framework, which is a major problem for an otherwise powerful library. Also -- and this is purely a matter of taste -- Prototype's super-pragmatic approach to things (like the heavy use of the innerHTML property) can seem a little "dirty" sometimes.

For smaller projects, the decoupled design and fully-featured components of YUI may well be a big plus. It's very easy to drop in the Connection Manager or the Event library and get going on some basic tasks without having to traverse too much of a learning curve. On the whole, though, it doesn't have much to offer in terms of cool or powerful features.

Dojo is definitely the daddy of the bunch -- you can almost always rely on it for the most powerful implementation of any feature. And Dojo's focus on performance is an absolute godsend if you're planning a very JavaScript-intensive application. The widget implementation also has enormous potential for building complex UIs. However it really is quite big -- both in terms of its file size and the size of the API -- so I wouldn't recommend it for smaller projects.

In my opinion, Mochikit is by far the most well designed and well thought out of the four, and Python/Twisted/Nevow developers will definitely find its API very familiar. However, its documentation is a bit thin in some places (for instance, I'm still a little unsure as to which version of the Mochikit distribution to put in the script tag). Also, some of the idioms and functional techniques that it uses may be confusing for beginners or those who aren't well versed in functional programming techniques. However, it really is worth a look. Mochikits's capabilities will probably surprise you -- the createDOM function, iteration tools and the asynchronous architecture are a work of art.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links

Rate This Article

  • 1
    Poor
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
    Great

Comment on This Article

Have something to say?

Post A Comment

You need to be a member of the SitePoint Forums to comment on this post. Sign Up

Already a member? Post using your SitePoint Forums account:

Follow SitePoint on...