Viewers: in countries Watching now:
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.
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 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.
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.
There are currently no FAQs about Prototype and script.aculo.us Essential Training.
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
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.