Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Working with the Enumerable class

From: Prototype and script.aculo.us Essential Training

Video: Working with the Enumerable class

Let's dive into the power of Prototype's collection classes by looking at the Enumerable class. The Enumerable class provides Prototype collections with a lot of power and utility. It addresses one of the most common scenarios in web development because Enumerable makes it easy to iterate or loop over many different kinds of objects in JavaScript and performs some processing logic on them and you run into this all the time in JavaScript.

Working with the Enumerable class

Let's dive into the power of Prototype's collection classes by looking at the Enumerable class. The Enumerable class provides Prototype collections with a lot of power and utility. It addresses one of the most common scenarios in web development because Enumerable makes it easy to iterate or loop over many different kinds of objects in JavaScript and performs some processing logic on them and you run into this all the time in JavaScript.

Typically, your code has to work with collections of all kinds, whether it's collection of elements or collection of attributes on elements or collections of data objects, this scenario comes up again and again. So if we take a look at how things are done the old way, this is a fairly common example in JavaScript. The code here is doing a getElementsByTagName call on the div tag name and that's going to come back with an array of all of the div tags in the element, and in the next line gets the length of the div's array and then we have a for loop with a loop counter and the loop loops over all of the divs, gets each one of the divs, and sets an attribute on the div. In this case, it's setting class to content.

So this is five, six lines of code. It loops over an array of elements and it's fraught with danger. You might make a mistake in the loop counter, you might go too far, you might not go far enough. If you operate on the array then the length is going to change. So let's take a look at how this same scenario is done using Prototype. Now using Prototype, Prototype's Enumerable class gives us a brand new function called each and here, you can see what we are doing is we are using the double dollar operator to get a collection of all the divs and then on that collection, we are calling the each function, which surprisingly enough is called for each element in the collection.

Now the each function takes as an argument, a function that will be passed each one of the elements in the collection, so you can do some processing on it. So in this case, my function is getting each one of the div elements and then I am just calling the setAttribute function on each one of the elements. So here in two lines of code, we are accomplishing the same thing that took four or five lines of code in the old way.

The each function alone is probably worth its weight in gold just including Prototype in your web development projects just by itself. This function pretty much makes Prototype worth including, the ability to do this kind of processing on collections. It's a big time saver. You notice it gets rid of the need to declare really any variables. I didn't have to declare any variables to hold the array. I didn't have to declare any variables to hold the length of the array or any loop counters. There is really nothing to go wrong here.

It's just a function that knows how many elements are there in the collection and iterates over each one. Now that we have seen how the each function works, let's take a look at the rest of the Enumerable class. There is a bunch of really great functions in here that help us with our web development scenarios. If you think each is great, just hold on because it gets even better. The first group of functions we are going to look at are used for retrieving information about a collection. So let's start off by looking at some of these functions.

You will notice that in some of the examples, there are functions that do the same thing. They just happen to be named differently. Prototype does this. They provide methods that perform the same task. They just happen to be named differently and the reason for that is because some of the functions are taken or borrowed from other browsers or programming languages. So in order to increase the comfort level of developers who come from various backgrounds, they name their functions more than one thing so that programmers with different experiences can use whatever is comfortable for them.

So the first example, all and every. The all function scans all of the elements in the collection and it returns a Boolean value, true or false, if all of the elements satisfy a particular Boolean condition. And you can pass an optional function that will be called for each element so you can do your own testing. If you don't supply that function then the all method will evaluate each element in the collection as if it were a Boolean. So null and zero and false and undefined will all evaluate to false, whereas other values like strings and numbers and objects will evaluate to true.

The next function, any or sum, is similar to all. It basically runs through the collection to see if at least one of the elements satisfies a Boolean condition and again, like the previous example, you can supply a function which can be used to test each element. The include or member method returns true if the collection contains the given value. Otherwise it returns false. The size function returns the size of the collection, kind of like the length on an array. Max and min find respectively the largest and smallest elements in the collection and you can provide an optional iterator function to test each element, so if you have a complex object, you can use that to determine what you consider to be large and what you consider to be small.

If you don't provide the function then the max and min methods will just evaluate each element and use JavaScript's internal logic to figure out what it thinks is largest and smallest. Finally, the pluck method retrieves an array of the values of a given property name from the elements of the collection. A common usage of pluck is to loop over a bunch of DOM elements and get a property from each one of them such as height or width or some other standard DOM property, but you can use on your own objects as well.

Okay, let's move on. These methods are for searching and filtering elements in a collection. So the detect or find method searches the collection for the first element that matches the criteria that specified by the function that you provide to it. Similarly, the filter or findAll or select function returns an array of all the elements that match the selection criteria and again you provide a function that helps it find the objects you are looking for.

The grep function uses regular expressions and if you are not familiar with regular expressions, there is a title here on lynda.com called Practical and Effective JavaScript Programming, which explains how regular expressions work. Essentially you supply a regular expression pattern and grep will use that pattern to search the collection and for all the matches it finds, all the elements that match the regular expression, it will call the optionally supplied fn function for each one of those matching elements so you can do some additional processing before it's returned in the result array that comes back.

The reject function performs the exact opposite of select or filter or findAll. It returns an array of all the elements that don't match the criteria, specified by the function that you give it. Finally, the partition method is kind of like a combination of select and reject. So, partition returns an object that contains two arrays. The first array contains all the elements that do match the criteria specified by the optional fn function that you supplied.

The other array contains all the elements that don't match and if you don't specify that optional function, then each element in the collection is evaluated as a native Boolean JavaScript element. So if again, for example, null, undefined, false, those all evaluate to false and strings and numbers and objects will evaluate to being true. Then next we have the methods for transforming collections and the elements that are in a collection.

So to begin with, the sortBy method takes a sorting function and we will sort the elements in the collection by calling that function, which is responsible for determining the order in which each element should be sorted. So you supply that function and it returns a value instructing the sortBy function to figure out where you have put it in the sorted collection. The inject method is pretty interesting. It takes a collection and derives a final value from the collection by accumulating an ongoing value over time.

So it calls the supplied fn function for each one of the elements in the collection and then your function can compute some value and add it to the accumulator. We will see an example of that in a bit. The invoke method invokes the given method name on each element using the arguments specified by the args parameter. You have seen me do this a couple of times throughout the course so far. You will see this used, for example, when you have a collection of elements and you want to invoke the same method on all the elements. For example, you want to invoke the hide method on a bunch of DOM elements.

The collect or map function returns an array of values, each of which are derived from the value of each element by calling the supplied function that you give it. So, for example, the collect function will call whatever function you supply and inside your function, you take each one of the elements and you calculate some value based on it and return it and collect will build an array of all those returned values. The eachSlice and inGroupsOf functions process the collection in groups of a certain size and finally, the zip function is pretty interesting.

We will see an example of that one as well. That merges together and you can think of the zipper on a jacket the way it merges the teeth together. This merges together two collections, calling the optionally supplied function for each one of the elements. You can get some really interesting results out of that and we will see some examples of that in a bit. So now that we have taken a look at a lot of these functions, it's probably instructive to see some of them in action. So, let's go over to the code and see some of these as they work. So here I am in the code and I have got the Enumerable_start example file open.

What you can see what I have done here is I have created a hash object and we will learn about hashes a little bit later in the course. Essentially a hash is a way of storing data in an object in sets of key/value pairs. So I have got an array of students that you might see in a school and each student has an ID number and an object that describes the student. Their name, their grade, what GPA they have and who their homeroom teacher is. So we can use this collection of data to try out some of the collection methods that we just learned about.

Let's begin by doing something simple. Let's use the collection methods to see if there are any students who have a GPA of lower than 2.0. So what I am going to do is write Students, that's the collection, and to do this, nw remember, we are looking for any students that have a GPA lower than 2. So we will use the appli named any function and we will pass in a function that takes an individual student and inside that function, we are going to take a look at the GPA of each student.

When each one of these elements in the collection is passed in, it's going to be passed in as an array. So the first elements in the array will be this value right here, the ID, and the second element in the array will be the object that represents the student itself. So what I need to do is get the student, return student at index 1 because arrays are zero based. Put this in some parens.

So return student 1 .GPA is less than or equal to 2.0. So this function will evaluate to true if any of the students have a GPA of 2.0 because remember, this function is going to be called for every one of the elements. So once we do that, we can wrap this in an alert. So we will save and we will jump over to the browser and we will see if that works.

So let's open this up in IE and we refresh and you can see that that function did in fact evaluate to true, because apparently there is a student with a GPA of less than 2.0. Let's go back to the code and you can see actually there is two of them. There is one right here, Eileen Lefty, and Ivy Leeg, they both have GPAs of less than two. So we know that that works, let's try some additional stuff.

Let's try getting a list of all of the students that have a GPA of greater than 4.0 because they are going to make it to the Dean's List. Let's define a variable, var DeansList equals and we will say students. Now in this case, remember, we are going to get a list of all the students that match this criteria. So that is the select function. Again, inside select, we will pass a function that takes a student each time and for each student, we want to return-- Now we are building an array here.

We return whether or not a student has a GPA of greater than or equal to 4.0 and what we will do is we will alert the DeansList. Let me take a moment and pause here. Because we are working with some pretty complex data, alerts are just simply not going to cut it. What I am going to do is use the built -in developer tools in the browser to inspect these elements as we are working on them and for IE, there are some developer tools built-in, but regardless of what browser you are using, if you are using Firefox, there is an add- on called Firebug or if you are using Safari, there are the same developer tools are built in there or Chrome, they also have the same thing.

You can use whatever developer tools are in your browser. I am going to use the ones built into IE and we will see those in a moment. So now that I have the code written, let's save it and let's go back to the browser and we are going to refresh. You can see that sure enough, there are three students that have GPAs greater than 4.0. So what I am going to do is bring up the window that lets me inspect elements and I am going to switch over to the script and I am going to put a break point on the alert so that we can see the results when I come back.

So I am going to start debugging, click OK so it refreshes, so you can see the break point's been hit and now we can inspect the DeansList object and you can see that sure enough, the Students.select function has created an array for us. They have three students in there and those students are, let's see, Adele Amberly and then we have Charlie Horse and we have got David Goliath. You can see that sure enough that one has a GPA of 4.9, 4.5, and 4.2.

So that's how the select method works. Let's go ahead and send this on its merry way. Let's go back to the code and try another example. Now let's try an example where we partition the students into seniors and underclassmen. So remember, the word partition. That sounds suspiciously like the partition method of the collection. So we will write partitionedStudents = Students.partition.

We are going to separate the students into two arrays based upon what they're seniors or what they are not seniors. So we have to write a function that checks to see if the student is in grade 12 and if they are in grade 12, they will put into one of the arrays and if they are not in grade 12, they will be automatically placed in the other one. So let's do that. We will write function, which takes a student. What we need to do is return whether the student-- And again I have to index that array there.

If their grade is equal to 12 and then let's put a point where we can set a break point, partitionedStudents. There we go. So remember, partition will create an object with two arrays in it. The students that are in grade 12 and the ones that are not. So let's go back to the browser. We will stop debugging and now we will refresh the content.

You can see that the results came back for the partition, but let's actually go in and inspect that content. So I am going to put a break point right there and we will fire up the debugger and now we will refresh the page so the break point gets hit. So here you can see the array that came back for the partitionedStudents. Here is this object and it's got, like I said earlier, partition makes two arrays. The one that matches the elements that did match the criteria and the ones that did not match the criteria.

So it looks like we have three students who are seniors. We have got Bobby Bumberlin, he is in grade 12 and we have got Ginger Snappy, also in grade 12, and we've got Horatio Caine also in grade 12. So if we look at the array where the students did not match, you can see that they didn't match because their grade is not equal to 12. So that's the partition method.

So, we're having a bunch of fun. Let's keep on going. Let's go back to the code and try some other stuff. Comment that out. Now that we have done partition and select and any, let's try something simpler. Let's find the students that have the highest and the lowest GPA. So we will have highest GPA equals students.max, because remember, max finds the maximum value.

We will write our selector function. What we are going to do is simply return the student's GPA and we will let the max function figure out which one is the largest. So we will just return student 1.GPA. Now we are going to do something very similar for the lowest GPA. So I'll just copy and paste this and rename this variable to be lowest. In this time, we are going to call the min function and we will return the same thing and then we will alert highest GPA.

And the lowest GPA. We probably won't need the debugger tools for this one. So let's save and let's jump back over to the browser and now we are going to refresh and you can see that the highest GPA is 4.9 and the lowest GPA is 1.8. That's max and min. Let's try one more example and this will be the most advanced one that we try. Let's go back to the code. Comment that out.

Now, we are going to use the inject function and the inject function is named that way because its borrowed from other what are called functional programming languages. they have this notion of a way of accumulating values over time. So what we are going to do is we are going to use the inject function to count all the students according to what grade they are in and store that in a result object. So let's define the result object first. We will call it studentCount and it's going to be an object and we will have a couple of properties in here.

So we will have grade 10s and we will start that off at 0 and we will have the grade 11s and that will begin at zero and then we will have the grade 12 and that will also begin at zero. So, this will be the variable that holds the results. We just need to call students. inject and inject is going to take the studentCount object, because that is the accumulator that we will be working on, and we need to define a function that's going to be called with each student.

So we define a function. This function gets called with two arguments. It gets called with the accumulator object, which will be this guy right here each time through, and it will be passed as this argument and it gets called with each one of the elements in the collection. So inside this function what we are going to do is just a couple of simple statements that count each student based upon what grade they are in.

So if the student's grade is 10 then we will update the grade 10 count, and we are going to do this with each one of the students so we will do it for grade 11 and we will do it for grade 12. So now that we have increased the count of each one, what we need to do now is return the updated object so that it can be used again the next time through the loop.

If you don't do this then the object or the accumulator rather will not get properly updated each time. So always make sure that you return the accumulator from each pass through the loop. Then we are going to just create a break point place so we will just alert student count. So let's save, go back over to the browser, let's just refresh really quick.

You can see that our student count object is being updated. So let's bring up the developer tools, take that break point off, put one on down here and refresh the page. So you can see that the break point has been hit and here is our studentCount object and you can see that the counts have all been updated properly. So there are four students in grade 10, there are four students in grade 11 and three students in grade 12. I hope this gives you a taste of the power of the Enumerable class.

This really, really makes Prototype an extremely powerful tool for building web applications. These kinds of scenarios happen all the time and Prototype, as you have seen, makes dealing with them a real breeze.

Show transcript

This video is part of

Image for Prototype and script.aculo.us Essential Training
Prototype and script.aculo.us Essential Training

49 video lessons · 7037 viewers

Joe Marini
Author

 
Expand all | Collapse all
  1. 2m 26s
    1. Welcome
      1m 19s
    2. Using the exercise files
      1m 7s
  2. 18m 4s
    1. Introducing Prototype
      4m 59s
    2. Downloading and installing Prototype
      4m 53s
    3. Writing a Prototype-enabled page
      5m 44s
    4. Exploring Prototype's features
      2m 28s
  3. 38m 9s
    1. Overview of Prototype content functions
      4m 42s
    2. Looking up elements with $()
      5m 14s
    3. Using the $$() selector function
      12m 32s
    4. Retrieving form element values with $F()
      8m 38s
    5. Getting practical: Annotating page links
      7m 3s
  4. 1h 5m
    1. Introducing the extensions
      1m 47s
    2. Using objects
      10m 54s
    3. Using strings
      15m 32s
    4. Using numbers
      7m 17s
    5. Using arrays
      7m 19s
    6. Using Prototype templates
      8m 9s
    7. Performing periodic tasks with PeriodicalExecuter
      7m 41s
    8. Using JSON support
      6m 51s
  5. 48m 2s
    1. Understanding the collection features
      2m 55s
    2. Working with the Enumerable class
      24m 51s
    3. Creating arrays with $A()
      3m 58s
    4. Handling ranges with $R()
      2m 46s
    5. Making Hash objects with $H()
      13m 32s
  6. 1h 2m
    1. Understanding Prototype's element class
      9m 0s
    2. Manipulating content
      6m 21s
    3. Traversing the DOM
      14m 24s
    4. Changing CSS and element visibility
      5m 53s
    5. Setting element positioning
      12m 38s
    6. Using other DOM element functions
      2m 32s
    7. Getting practical: The automatic table of contents generator
      11m 26s
  7. 41m 2s
    1. Understanding the Prototype event class
      5m 6s
    2. Observing events
      11m 45s
    3. Getting information about events
      8m 28s
    4. Creating custom events
      8m 43s
    5. Getting practical: Table striping and highlighting
      7m 0s
  8. 25m 59s
    1. Creating and handling AJAX requests
      12m 25s
    2. Using the Ajax.Updater
      8m 40s
    3. Handling periodic updates
      4m 54s
  9. 25m 36s
    1. Introducing script.aculo.us
      4m 37s
    2. Using visual effects
      7m 7s
    3. Using drag and drop
      4m 47s
    4. Using autocomplete
      5m 23s
    5. Using sliders
      3m 42s
  10. 54m 10s
    1. Getting started
      4m 50s
    2. Displaying information dynamically
      14m 32s
    3. Filtering data
      19m 32s
    4. Building an image rotator
      15m 16s
  11. 19s
    1. Goodbye
      19s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Prototype and script.aculo.us Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.