Join Joe Marini for an in-depth discussion in this video Understanding the collection features, part of Prototype and script.aculo.us Essential Training.
- View Offline
In this chapter we are going to talk about working with collections in Prototype. And in my opinion collections are one of Prototype's best features. This provides Prototype with the ability to work with sets or collections of elements. It's very powerful and it's one of the cornerstones of the Prototype library. When you think about it, you run into this situation all the time when you are working with various Web scenarios. For example, when you are getting elements out of the page, that's a collection.
Or you have to work with the attributes on an element. You know that's a collection. Or you have a set of data objects that represent employees in a department, you know that's a collection. So Prototype makes it really, really easy to work with collections of objects. Collections come in the form of arrays, hashes, ranges or custom objects that you create yourself that use a Prototype class called Enumerable. And Enumerable is the source of much of the Power of Prototype's collection objects.
And all the other classes, like arrays, hashes, ranges, they mix in the Enumerable class, which is what gives them their collection power. And there is the $A() operator which creates an array out of any set of objects it's given. So for example, you can call the $A() on the results of document.getElementsByTagName, the standard built-in DOM method, which doesn't return an array.
It looks like one, but it's not. So you can use $A() for that. Then there's the $R(), which creates a range and ranges can be pretty much just about any thing, numbers, letters and we'll see that a little bit. And then finally there is the $H(). And $H() makes working with what are called hash objects really very easy. Once you've start working with hash objects, these are one of those kinds of objects where you find yourself saying, Wow! How did I ever get along without working with these before? So now that we have the overview of what collections in Prototype are, we can start working with them.
- Retrieving and manipulating web page elements
- Handling web page events and creating custom events
- Traversing the DOM
- Creating and handling AJAX requests
- Using script.aculo.us controls such as Autocompleters, Sliders, and Visual Effects
- Building complex page features like data filtering and image rotators