Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb
"Accelerated DOM Scripting with Ajax, APIs, and Libraries"
question').each(function(el){ Event.observe(el , 'click', (function(){ this.next().toggle() }).bindAsEventListener(el)); }); There??™s a bunch of things happening in this example. First is the $$() function, which retrieves any element on the page with a class name of question. This function returns an array of elements. Because it is an array, you can now use the Array.each() method that the Prototype library makes available to you. It takes a function as its sole parameter, executing it for each element in the array, with the element getting passed into that function. Within that anonymous function, a click event handler is attached to each element. The element is bound as the event listener to access it from within the event handler by using the this keyword. When a user clicks a question, the function will grab the next element and toggle its visibility. With this level of succinctness, you can lose readability. There are ways to write the code to make it easier to read, but it??™s often at the cost of brevity. Here??™s a quick example that uses named functions instead of anonymous functions to improve readability: function onEach(el) { function toggle() { this.next().toggle(); } Event.observe(el, 'click', toggle.bindAsEventListener(el)); } $$('.question').each( onEach ); Prototype??™s approach to object-oriented design is firmly in the object literal camp. A constructor can be created by specifying an initializing function: