Perfection kills

Exploring Javascript by example

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 »

Archives Posts

Meet Proto.Menu – simple context menu class

August 20th, 2007 by kangax

Context menus are a great way to enhance user experience when used appropriately. About a half year ago, I needed one. There were few decent solutions out there but none of them was what I needed. YUI menu seemed like a solid solution but was just too much, as I only needed basic set of features. After spending couple of days figuring out all the right-click browser quirks Proto.Menu was born – a simple class on top of prototype.

Few days ago, playing with new release of prototype, I realized how much this little context menu script would benefit from new DOM builder and other 1.6 goodies. The class was almost completely rewritten and while at the same ~2KB, it now has a set of useful options and is more cross-browser than ever : )
In case anybody was looking for something like that, you might want to give it a try

Filed under Proto.Menu, extension having 15 Comments »

« Previous Entries