Article on Writing Custom Iterators for Prototype from Encytemedia

via ajaxian: read the full article

The DOM can be a painful beast at times. When you ask for the childNodes of an element, most of the time you’re just wanting the element nodes only and you’d like to completely ignore the text nodes. Using Prototype, you could write something like the code below:

element = $(element);
element.cleanWhitespace();
$A(element.childNodes).each(function(element) {
  element.setStyle({color: '#ccc'});
});

That would be a quick fix, but remember, we’re not supposed to be repeating ourselves. I find myself wanting to perform a task like this time and time again. Basically the code above just grabs a parent element, cleans the whitespace from it (removes the text nodes) and gives us back only the elements which we wanted to begin with. It’s much simpler to DRY up this process by implementing our own custom iterator.

The eachElement Method

We can easily reuse the code above by appending an eachElement method to the Element.Methods object.

Element.addMethods({
  eachElement: function(element, iterator) {
    element = $(element);
    element.cleanWhitespace();
    $A(element.childNodes).each(iterator);
  }
});

Now that we’ve got this in place, it’ll make our life a lot easier, our code a lot less redundant, and anyone who reads our code will probably have a better understanding of what we’re doing. Never mind the fact it just rocks being able to do something like this.

$('options').eachElement(function(element) {
    console.log(element);
  });

Leave a Reply

You must be logged in to post a comment.