perfection kills

Exploring prototype by example

Archives Posts

So you want more documentation?

September 24th, 2007 by kangax

Have you ever heard of prototype? I’m sure you have, since you’re reading this blog. Many things make this library a weapon of choice for developers all over the world. The way work is done with prototype is simply mind blowing - concise and expressive code, full range of tools for the job just seem to make a dream come true. One day, though, you run into problems - things just don’t work the way they’re supposed to. You open your browser, point it to google and… dark side of prototype reveals itself in its full glory…

No, I’m not trying to sound dramatic, but the fact is that prototype is notoriously famous for the lack of down-to-earth documentation. For javascript ninjas, quick glance over source code should clear all the confusion. For the rest of us, there’s a wonderful place called API reference. This should be your first bookmark on the way to perfection. The sad part is that not everyone understands API reference. People demand easy to follow tutorials, out-of-the-box solutions and lower taxes.

For all of you - lazy bastards - out there, here’s a list of must know resources:

Official documentation

Prototype API reference
Script.aculo.us wiki

News groups:

Google groups, RoR Spinoffs - Number 1 place to look for answers, ask questions, get help quickly. Some really smart folks help hundreds of people with most twisted problems (yes, you’re right, 90% are IE related)

Google groups, Prototype: Core - Once you know prototype’s source code by heart, feel free to join this group to discuss the inner essence of prototype’s magic. Other than that - great place to search for issues that might have already been solved before.

Core developers’ blogs

Tobie Langel
Andrew Dupont
Thomas Fuchs
Justin Palmer
Dan Webb

Not core developers’ blogs (but still very educating)

Matt Foster
Ryan Gahl
Samuel Lebeau

Other resources

prototype @ Ajaxian

Offline documentation

Prototype API
Script.aculo.us Docs

That’s about it.

Did I forget something? Feel free to add more links in comments.

Good luck and happy prototyping…

Archives Posts

Extending the limits

August 28th, 2007 by kangax

One of the beauties of prototype is in the way it allows us to extend its functionality. Building custom snippets of code has never been easier. The philosophy behind it is to keep core-level things at a minimum, but provide a convenient way to extend them.
The magic method is Element.addMethods

The syntax is quite simple:

Element.addMethods({
  method1: function() { ... },
  method2: function() { ... },
  ...
})

When defining a custom method, make sure that:

  • First passed argument is an element
    Element.addMethods({
      myAwesomeMethod: function(element, ... ) {
        element = $(element);
        ...
      }
    })
  • That same element is returned from the method (and is therefore chain-friendly)
    Element.addMethods({
      anotherAwesomeMethod: function(element, ... ) {
        element = $(element);
        ...
        return element;
      }
    })

We can also skip “var” when assigning element reference (since it’s passed as a first argument).

As an example, here’s a little helper, that I use quite often to display notifications (usually when form verification fails). We will update element with content, make it appear, wait couple of seconds and fade it out.

Note: The following example uses prototype version 1.6.0_rc0 and requires Scriptaculous’ effects module:

Element.addMethods({
  flash: function(element, content) {
    element = $(element);
    new Effect.Appear(element, {
      beforeStart: function() {
        element.update(content);
      },
      afterFinish: function() {
        Effect.Appear(element, {to: 0, delay: 3,
          afterFinish: function(){
            element.hide().setOpacity(1);
          }})
      }
    })
    return element;
  }
})

Now we can simply do:

$('errorBox').flash('login field should not be empty');

Try it out! Pretty convenient, huh?

Just to get you started, here are few more examples that might be convenient in every day use:

1) Form#populateFrom

Ever wanted to populate form via ajax? All it takes is a few lines of “magic”:

  • Description: Fills form with data via json (requires: v1.6.0_rc0+, ‘Content-type: application/json’ header)
  • Usage: $(’myForm’).populateFrom(’blah.php’);
  • Invoked on: Form
  populateFrom: function(element, url) {
    element = $(element);
    new Ajax.Request(url, {
      onSuccess: function(response) {
        var data = response.responseJSON;
        element.getElements().each(function(el) {
          el.setValue(data[el.readAttribute('name')])
        })
      }
    })
    return element;
  }

If your server-side script returns something like:

{
  "firstName": "Fluffy",
  "lastName": "Horse",
  "email": "far@far.away"
}

then invoking this method

$('myPrecious').populateFrom('myScript.php')

on a form with the same structure

<form action="foo.bar" id="myPrecious">
<input name="firstName" type="text" />
<input name="lastName" type="text" />
<input name="email" type="text" />
</form>

will populate JSON data into a form

2) Element#__extend

This one is a real gem and I find myself using it all the time. The idea is to be able to extend element with arbitrary number of methods/properties in a chain friendly manner.

  • Description: Extends element with a hash of properties
  • Usage: $$('input#firstName')[0].__extend({initialValue: 'John'}); $$('form').invoke('__extend', {counter: 0})
  • Invoked on: Any
__extend: function(element, hash) {
  return Object.extend($(element), hash);
}

As you can see this one is just a simple one-liner so we can easily skip explicit element assignment.
As an example of a real-life case, here’s how I used it in a Proto.Menu class:

new Element('a', {
      href: '#',
      title: item.name,
      className: item.className || ''})
  .observe('click', this.onClick.bind(this))
  .update(item.name)
  .__extend({
    _callback: item.callback,
    _disabled: item.disabled ? true : ''
  })
)

As you can see, it’s really convenient to store such things as callbacks, identifiers and boolean values as custom element properties. It’s also worth mentioning that Prototype 1.6+ extends observed elements with _eventID (preventing duplicate observers) in a similar manner.

Element#setUniqueClassName

Another common use case is when we need to assign a class to an element, removing it from its siblings at the same time. Most trivial example is setting “selected” or “active” class on navigation links

  • Description: Sets className, removing className from all siblings
  • Usage:$$('#nav li a')[0].setUniqueClassName('selected')
  • Invoked on: Any
setUniqueClassName: function(element, className) {
  var element = $(element),
  if (!element.hasClassName(className)) {
    collection = element.next() || element.previous() ? element.siblings() :
      $A(element.up(1).getElementsByTagName(element.tagName));
    collection.invoke('removeClassName', className);
    element.addClassName(className);
  }
  return element;
}

This method only starts iteration if current element does not have a specified className (in case already selected link was clicked). It’s also smart enough to iterate over child nodes of parent node siblings (since semantically-correct markup should contain links inside of list items). In this case, it will try to collect all <a> elements first and then iterate over them.

I hope you enjoyed this tutorial and are inspired by all the possibilities of prototyping : )

Archives Posts

We don’t need no stinkin’ “new”

August 21st, 2007 by kangax

There seems to be a bit of confusion among people not too familiar with Scriptaculous library. I often hear questions like “Why is new Effect.BlindDown('myElement') is not working? Am I not passing myElement correctly?”. No, the situation is much simpler.

As of 1.7.1 Scriptaculous has 6 Core Effects:

All of the core effects should be INSTANTIATED. This means that we use “new” keyword in front of them:

new Effect.Opacity('myElement');
new Effect.Move('myElement');

Even though the correct syntax is clearly stated in wiki, it is sometimes not obvious and could be easily missed. These kind of things could make beginners bang their head against the wall for hours.

On the other hand, there is an extensive set of Combination effects:

These do NOT need “new” keyword and essentially are just static methods of Effect object:

Effect.Shrink('myElement');
Effect.SlideDown('myElement');

I hope this clears all the confusion

Filed under Script.aculo.us having 6 Comments »