Prototype Gets Some Serious Syntactic Sugar

—Tuesday, March 07 2006

I’ve hoped for a while that Prototype would implement something similar to what JQuery has going on for DOM elements. The current Element object in Prototype is packed full of great stuff, but how you access those methods isn’t exactly ideal.

Here is an example of something you might have done using Prototype:

   this.element = $('element');
   Element.hide(this.element);

Now we can do this:

 this.element = $('element');
 this.element.hide();

All of the methods of Element are now accessible this way. We can even access Script.aculo.us effects this way too.

 $('element').visualEffect('highlight');

Now thats just sweet stuff. Want to add your own methods to Element? No problem!

   Custom = {
     contrast: function(element) {
       var actor = $(element);
       actor.setStyle({color: '#000', backgroundColor: 'yellow'});
       return actor;
     }
   }
   
   Object.extend(Element.Methods, Custom);

Now we can call the contrast method above in the same fasion:

  $('element').contrast();

It’s not all good though, there are some things you can’t do such as chain methods of Element together or any other method that doesn’t return a node. The code below will not work.

$('element').setStyle({color: '#ccc'}).show();

However, this will work:

//Works
$('element').contrast().show();

//Doesn't work
$('element').show().contrast();

I expect we’ll see Element evolve in the future and allow us the ability to chain methods.

Thats a quick rundown of the new features. Until next time–Happy Prototyping!