with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

jQuery wins the Event Selector Showdown

Sunday, May 21st, 2006

Having come across this blog post on the jQuery Blog, I was immediately fascinated by the amount of effort library developers are putting into language philosophy. With only a few characters of code, jQuery was able to bind events to two sets of list groups that would set the style of the element you clicked on. Indeed, I was most definitely impressed and wondered to myself how I could get this done with Yahoo! UI utilities.

Sweet! But why?

So we saved a couple lines of code. For the sake of chipping into the group I added a comment displaying how we can get this same thing done with the Yahoo! UI DOM and Event utilities.

YUI Challenge

YAHOO.util.Event.on(
	[YAHOO.util.Dom.get('item').getElementsByTagName('li'),YAHOO.util.Dom.get('otheritem').getElementsByTagName('li')],
		'click',function(){ YAHOO.util.Dom.setStyle(this,'color','#c00'); });

The fact of the matter is, although YUI doesn’t win the Event Selector battle, you have to take into account that that’s not what it’s out to do. The jQuery is definitely smaller because it uses the ‘$’ dollar symbol as a namespace, which is, sexy by appearence; but not always practical.

One thing to note about YUI utilities is that it’s not here to change the way you think about writing JavaScript, and as a matter of fact you’ll find it very dissimilar to libraries like Prototype, Behavior, Event:Selectors, or jQuery. But rather YUI takes out the cross-browser heavy lifting so you don’t have to (which other libs do too). It comes with class management, style getting/setting, batching, getting Elements by “whatever”, and a few others… and that’s just in the DOM util. The Event utility also takes out some heavy lifting with a few other features that most other utilities haven’t dug into with perhaps the exception of Dojo which is customEvents.

What gives with the YAHOO namespace?

One common complaint you might hear about YUI is that everything is YAHOO.foo.bar.MyDaddyCanBeatUpYourDaddy. Fair enough. It’s not quite as sexy looking as the dollar symbol - but in practicality, it’s for your own good. You really should be thanking the team that they’ve done that for you since it is very unlikely that Yahoo! code is ever going to clash with yours (ok, no need to “thank,” but just know that it’s a good thing).

It allows for better code organization and it keeps a visual hierarchy of how the libraries are laid out. If it’s a utility, expect it to live under YAHOO.util, if it’s a widget (not to be confused with Konfabulator), expect to find it under YAHOO.widget. Likewise if has something to do with Ajax, expect to locate it under YAHOO.util.Connection. Make sense?

Unlike Prototype.js, you may have to worry about collisions such as Event, Element, or Ajax; all of which live under the global namespace. But I’m sure that’s nothing Sam Stephenson hasn’t got flack for before - not to mention it doesn’t stop people from using it anyway. Indeed, I’m still using Prototype for my UDASSS script, but soon enough, I will be changing my ways. All in all, the choice is up to the developer. Use what you’re most comfortable with.

21 Responses to “jQuery wins the Event Selector Showdown”

  1. Dan Webb

    Hey Dustin, really interesting post. I’ve posted a response over here:

    http://www.vivabit.com/bollocks/2006/05/22/javascript-and-namespaces

  2. Dean Edwards

    For my own good? I’m a programmer. I hate typing.

    YAHOO.util.Dom.get(’item’).getElementsByTagName(’li’)

    That’s just silly.

  3. Justin Palmer

    I tend to agree with Dean here. Also reading Dan’s post, I don’t think verbosity is a bad thing when used sensibly.

    The one reason why I don’t give JQuery a deeper look is because I’ve skimmed the code and it’s almost impossible to get an idea of what’s what because of the brevity in variable and method naming. Otherwise, I think JQuery is a solid library.

    This is one thing Sam does right with Prototype. It’s just verbose enough that you can understand it. Although I admit that some of the inheritance bits are really hard to grok if you don’t spend time and go through a few WTF’s or so. Using something like Dean’s Base.js would solve this problem, not to mention the additional benefits.

  4. Dan Webb

    Yeah, Prototype’s style of inheritance initially seemed like a nice solution but I find working with it quite painful now. We do need something a little more powerful (like Base.js). I’m losing a little confidence in Prototype as time goes on though. There’s been a couple of big design choices that I think are going to spell trouble for them in the future.

    With jQuery, I agree, super short variable names aren’t really the answer to concise code but I’m definately a fan of short APIs as long as they are readable. One other thing that’s great about jQuery is the pluggable design.

  5. Dustin Diaz

    Dean and Justin,
    Sheesh, wasn’t expecting Mr. cssQuery and Event:Selectors to show up :). I still tend to agree that it’s for the better to have it namespaced. Sure it might be silly to write that long bit out. But you can do what you will with it. Create your own private shortcuts if you want. You’ll notice in my tetris game that I went ahead and did this:

    var DED.games.tetris = {
    YUD = YAHOO.util.Dom;
    YUE = YAHOO.util.Event;
    // my personal app here
    };

    In Simon Willison’s YUI notes he decided that having a nice ‘$’ dollar function was handy, so he went ahead and did the following:

    var $ = YAHOO.util.Dom.get;

    The point of the matter is you can make your own level of practicality.

    Dan, I concur that short vars aren’t the answer especially when the entire framework is built off of it. But as I mentioned, the choice is up to the developer. I can most definitely see what makes jQuery attractive for some people.

  6. Justin Perkins

    > I’m losing a little confidence in Prototype as time goes on though. There’s been a couple of big design choices that I think are going to spell trouble for them in the future.

    Care to ellaborate on that one Dan, maybe not here but perhaps another entry on your site is in order? ;)

  7. Dean Edwards

    OK. I’m gonna stop wailing on the Yahoo library now. It’s a good library. :-)

    To balance things out, what you gain in brevity using JQuery you lose in readability. It’s all swings and roundabouts…

  8. Dean Edwards

    Oh. And I have to second Justin. I’d like to read “Dan Webb reviews Prototype” on the vivabit blog sometime soon. ;-)

  9. Dustin Diaz

    @Dean and Justin: Agreed. Let’s hear it Dan :)
    Also Dean, All things aside, I think we can fairly say that we’re all guilty of turning this into a contest that shouldn’t be going on. All these recent libraries are freakin’ brilliant and I think sometimes we lose sight on the end-goal. Nitpicking rarely helps yet we all do it (Yea, I’ve been known on ocassion to nitpick).

    This is one reason I can’t help but stress (now) for developers to just go what they’re most comfortable with.

  10. Scott

    The only problem I have with the YUI namspace is the inconsistancy in the capitalization. YAHOO.util.Dom(?). I’m always mistyping the casing. Can you, or someone on the YUI team, elaborate on the bipolar casing scheme? :)

    Why is YAHOO all caps? Wouldn’t Yahoo achieve the same effect? Why not all lowercase?

  11. Dean Edwards

    Agreed. The new JavaScript libraries are all of a very high standard. But our analytical minds just love to nitpick! ;-)

  12. Dustin Diaz

    @Scott: The casing of the name chain is actually very consistent across all the utilities. YAHOO first off is just the initial namespace. It’s in all-caps to avoid collision. I would say that it’s very very very unlikely that this gets overridden. Beyond that, the second extension is generally to map out your primary path such as ‘util’ or ‘widget’ or ‘example’. Those are all lowercase. If we branch off into ‘util’ land you’ll see that from that point we have core classes.

    Although JavaScript doesn’t have a formal notion of a class, we like to mimick Java in the sense that we capitalize the first letter to give attention that it is indeed a Constructor. That’s why you’ll see things like ‘Event’, ‘Dom’, ‘Anim’, and ‘Connection’ - all of which have the first letter capitalized. Then beyond that, the methods based off those are indeed mostly all lowercase.

    I hope that helps clear up a few things. I can definitely see your point of view when looking at it for the first time.

  13. kentaromiura

    I agree with Dustin, and to comment #5 I must add that the object shortcuts is faster then Properties Lookups

    so
    YAHOO.util.Dom.foo();
    is always slower then
    YUD.foo();

    (..for this issue is better write

    var max=foo.length;
    for(var i=0;i

  14. kentaromiura

    emh.. sorry:

    var max=foo.length;
    for(var i=0;i<max;i++){/*..*/}

    is better that

    for(var i=0;i<foo.length;i++){/*..*/}

  15. Justin Palmer

    I’ve touched on “what I think is wrong with Prototype”:http://encytemedia.com/blog/articles/2006/05/23/prototype-inheritance-madness

  16. Justin Palmer

    Dustin, you should consider noting what type of formatting you allow in comments. So far, I’m 0 for 1. :-) Prototype: Inheritance Madness.

  17. Dustin Diaz

    Justin, I often screw up comments on my own blog. I’ve been the laziest of all when it comes to enforcing any kind of commenting restrictions. I should enforce something like textile. Other than that, the last time I had something here to help the people who commented, I had started to write something called ddCode but then failed to implement it. Sorry ’bout that :(

  18. Dan Webb

    Justin: Excellent article you have there. I was just poised to blog about this and one or two other sticky aspects of Prototype but you’ve beat me to it. Object.extend() is painful to code with and it would be great to see a more fully features ‘class’ system in Prototype because it’s one of a very small number of weakpoints.

    I still might do a review of Prototype too so I can add my two cents :)

  19. Weibing

    I find the code

    
    YAHOO.util.Dom.setStyle= ("item", "width", "100px");
    

    didn’t take a instant effect.

  20. Dustin Diaz

    @Weibing,
    That’s not how the utility works. Subtract the = equals symbol since you’re not supposed to assign the function to anything.

    Try this:

    YAHOO.util.Dom.setStyle('item','width','100px');
    
  21. Ali

    is there any post on yahoo util?

Leave a Reply

Phone Number:

If you're about to post code in your comment, please wrap your code with the tag-combo <pre><code>. Also please escape your html entities - otherwise they will be stripped out. I recommend using postable.

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

Flickr

Submit a Prototype

All content copyright © 2003 - 2007 under the Creative Commons License. Wanna know something? Just ask.

About | Archives | Blog Search

[x] close

Loading...

Submit a prototype

By checking this prototype I agree that I am not submitting false credentials, pornography, or a hate crime website. I also understand that by submitting my entry I may or may not be accepted, and if accepted, my entry may be taken down at any given time if I violate these terms.