- Overview
- Transcript
4.1 $.each and Templating
While not as glamorous and fun as working with effects, many of jQuery core's utility methods will be of tremendous help to you. In today's lesson, we'll review $.each
, and a basic form of templating, which will allow us to keep from embedding lots of nasty HTML into our JavaScript.
1.Introduction1 lesson, 00:38
1.1Welcome00:38
2.The Basics7 lessons, 1:33:04
2.1Hello jQuery10:52
2.2Not So Fast, jQuery06:54
2.3The Basics of Querying the DOM15:21
2.4Events 10119:58
2.5Events 20115:21
2.6Bind...Live...Delegate...Huh?10:49
2.7Creating and Appending Content13:49
3.Effects9 lessons, 2:39:59
3.1Slides and Structure23:46
3.2The this Keyword09:35
3.3Modifying Effect Speeds05:47
3.4Creating Custom Effect Methods07:16
3.5Full Control With animate21:34
3.6Homework Solutions12:15
3.7The Obligatory Slider (First Attempt)32:50
3.8Prototypal Inheritance and Refactoring the Slider34:03
3.9Your Questions Answered12:53
4.Utilities4 lessons, 59:31
4.1$.each and Templating12:49
4.2Say Hello to Handlebars15:09
4.3The Twitter API22:11
4.4Filtering with jQuery.grep09:22
5.Custom Events1 lesson, 25:17
5.1Custom Events and the Observer Pattern25:17
6.AJAX5 lessons, 1:33:13
6.1Loading Pages Asynchronously11:10
6.2Interacting with the Server-Side11:24
6.3PHP and jQuery: Part 122:37
6.4PHP and jQuery: Part 228:30
6.5Deferreds19:32
7.Plugin Development1 lesson, 45:57
7.1Head First Into Plugin Development45:57
8.Exit1 lesson, 01:06
8.1Goodbye01:06
4.1 $.each and Templating
[NOISE] Well welcome back to 30 days to learn jQuery. My name is Jeffrey Way, and in this chapter we get to take a closer look at some of jQuery course methods. Lots of utility methods that will be extremely powerful to you. They're not as fun as maybe the animate method, but you'll find that you'll likely take advantage of them much more. Things like jQuery.each, jQuery.map, jQuery.grep. Really powerful stuff that you need to know for your projects. So in today's lesson, we're going to take a look at jQuery.each and also take a quick stab at creating our own templating solution. So let's get started. What we wanna do is have an object that we can filter through and take its content and put it on to the page. So we'll do that right now. We'll say, var content equals this object like so. And for now we'll simulate maybe the log information. Maybe you're grabbing a JSON feed or something. We'll simulate that. We'll have title, and that title will be, My Awesome blog post. And for the thumbnail, let's simply go to one of my sites, net tuts. And we'll past the link in there. Remember, for actual projects you don't want a hot link, but as it's an enVato site, I think it's okay. Now how would we create multiples? So we have a title and thumbnail. That's all we're going to work with. We're not going to have content or anything. We just wanna get this on the page for demonstration purposes. But how can I do another one? Well, I can't do this, because then we have two titles in the same object, and that's not going to work. So what we'll do instead is content is going to be an array, so I'll wrap that within brackets. And then it's an array of objects. That's pretty neat huh? And now we can separate each entry within it's own object. So I'll copy all of that, paste it in. My second awesome blog post, and we'll come back and we'll grab this new relic thumbnail and paste it in, like so. And that's all we're going to work with here. We have two posts and we need to figure out how can we get this content on the page. Now what a lot of people will do, especially newcomers is they will create all of that html in their JavaScript. So maybe they will create the H1 and then they would set the text to it, and they would do content.title, things like that. And they just use string concatenation to build up this HTML fragment, and then they throw that into the DOM. But that's really messy, and then you're mixing all of that HTML and your JavaScript. There's probably a better solution, so let's try to create our own template. And we'll use the simplest form possible, and then we'll begin to take a look at more advanced solutions later in this course. So, we can create a template by placing it within script tags. And we'll give it an ID of blogTemplate. Now we also need to give it a type. And the only thing here is we wanna make sure that it is not parsed as JavaScript. And tech slash JavaScript is the default type for script. And we simply wanna change this out for anything. So we'll say tuts slash template. No within here we create our template so we're going to have an h two tag and we need to represent what the title will be, so I'm going to use curly braces. Title, two curly braces then the property name then closing two curly braces. There we go. And then we need to do the same thing for the thumbnail so img source equals thumbnail. And then I'll set the alt equal to title. So now, the image will be created. We're gonna set its source equal to the thumbnail, and we're going to set its alt attribute equal to the title. And there is our simple template. You can certainly have more. In a real world situation, you'll probably have information for the date or the author or the content. Anything that you would want to pull from a feed dynamically. So now that we have our template, how can we attach it? Okay, we'll let's figure this out. We've created our content, next let's store a reference to that template. So we'll call that template equals Jquery, jump in to the DOM and look for an element with an ID of blogTemplate. Now, in this case, we don't want to reference to the node. We want the html it's self. So I'm going to use jQuery's html method to take that out. And now if we console.logTemplate and we view this in the browser. You can see that we have that fragment right there, but we do have some white space. So let's take advantage of jQuery.trim, this is another help method we can use, and that will trim any white space off the beginning and the end of whatever it's passed. So now if I reload, you'll see that that jumps up. Now, we also have this link from the previous lesson, we'll get rid of that entirely. So now that we have a reference to the template,. We want to search through the template and replace all occurrences, in this case of curly curly title, close curly curly, with whatever is stored within the title property. Okay, well that should be pretty easy. We begin by filtering through this array. So we've learned that we can grab something with jQuery. And then call the H method to filter through it, but how do we do this when we aren't jumping into the DOM. We already have something to work with. Well, in that case we use jQuery.each. Now, jQuery.each accepts two parameters, and let me jump down just a bit. The first parameter is going to be what is the array that we're working with? We can also use an object. We are going to filter through content. For each item in the array, we are going to run a function. But now how do we know what is passed to this function? Will the index be passed, will a value itself, how can we figure this out? Well, we can either go to api.jQuery.com. Or, as we've learned, we can refer to the jQuery source. Let's do the latter. I'm in the jQuery source and I'm going to look for each. And that's going to come up a bunch of times. So let's do each colon. Here we go. And what we want here is right here, a special fast case for the most common use. So it begins by saying, are we working an object or an array? We're working with an array, so this fires. And what it does it just runs a force statement. So it filters through there, and the callback, that was passed as a second parameter. So there's our callback. That anonymous function. And what it does it uses the call method that we learned about. It calls it, it sets that current item in the array equal to this. And then as the first parameter it passes through the index. And as the second parameter it passes through the value. Okay, so now we know we can replace this with index, val. And let's try these out now. Console.log index. And then one more for the vowel. Reload, and as we expect we get zero then the object. Zero and the object. And notice that in each case this first object is equal to the first posting and the second one is equal to the second posting. All right so now if it's easier we can replace this with obj and we want to filter through template and update all of those instances of the curly braces. And we can use regular expressions for this. So we can say template.replace. And with regular expressions, I'm not going to go other this too much. That requires an entire course on it's own, and we even have one on Tuts premium if you'd like to learn more about that, I created it. So we're going to search for, within our regular expression, title. We're just going to search for that exact string. You can copy that, and paste it in here. Now I'm also gonna pass some flags. I'll pass the i flag, which means we can capture lowercase title, or if they have. Uppercase T, that will be captured as well. We're not worried about capitalization. And then I'm also gonna pass the g flag. Which means global. Continue searching. So normally it will find title. It'll go, I found it. And then it'll turn around and come back. But by specifying global we can say, okay you found it, good job. Now keep looking for any more occurrences. We're gonna search globally. Now, if it finds anything there, we're going to replace it with, well, we know that obj is this object right here, for each iteration. So, we'll replace it with the contents of obj.title. So we essentially replace it with that string. Now let's store this in a variable for now. And console.log temp to see if it worked. I'll reload and check it out. We've replaced the curly braces and title with my awesome post and the next one. Now we can stack replace. So let's do this right here, template.replace, and then we're going to do another one. And I will copy and paste all of this. And this time we're going to replace thumbnail with obj.thumbnail. Now let's try it, reload and now we've updated everything here. So take a look even though we can definitely improve upon this a little bit in future lessons because we are hard coding these values. But we can find a way to do that dynamically. But the advantage to this method is. Notice that nowhere within our JavaScripts do we have lots of messy HTML. HTML doesn't belong in the JavaScript, sometimes we do it because we have to, but templates make it really easy to separate that out. So now we know that the temp variable is equal to our modified HTML string. Now we simply need to add that to the DOM. So we don't have anywhere specific. We will simply apply it to the body element. So jQuery.body, or document.body, and we're going to append temp, let's try it. Refresh and there we go, pretty neat. And what's cool about this is if more is returned, for example, I'll copy that, and we'll use this to simulate a third posting. It filters through all of those, you don't have to do anything else. It just knows to filter through every object in the array and add it to the page. And then of course you would wanna add links or whatever it is. Now, a question that often comes up is, is this something you wanna do with JavaScript? If JavaScript is disabled, the user never sees these postings, and, absolutely, we are not mimicking a blog engine at all, we're mimicking, maybe you want to use JavaScript to pull in your favorite blog speed for the side bar. That way, it doesn't really matter if JavaScript is disabled, you don't display it. But if it is, maybe every 30 seconds you can use HX to pull in the latest news announcements from CNN.com. This is what you could use that for. And in most of those cases, this array will be replaced a Json response that you would query CNN.com and it's Json service. That will return a bit of Json and then you filter through that and put it onto the page. And we're going to learn a lot more about that in the HX chapter. So, the important take away for today's lesson is we use jQuery.each to filter through an array or an object. In our case, we filtered through the N array. And for each iteration in the array we take that template and we replace it with the unique information from the object that we're currently on. And then, we append that to the DOM. But there's something I want you to be aware of. What if this is a list of 50 items in the array? Well, in that case, for every iteration. We are appending something to the DOM, and this may not be the best idea. For two items it really doesn't make a difference, but you'll likely be dealing with a lot more, and that's a bad practice to be throwing stuff into the DOM. Every single iteration, that really effects performance. Instead, it would be better to build up a string and then throw that string into the DOM exactly once. And there's lots of different ways. I'll show you the easiest way for now. We'll create a new variable called frag and we're going to filter through this. And for each one, rather than appending to the DOM, we are going to say frag plus equals template.replace. So then at that point we can console that log frag and you'll see that we are adding our updated template. You'll see undefined right there. Let's set frag equal to a string by default, an empty string. And that will get rid of that. Now, you'll notice on the first iteration, frag is equal to that single posting. And then on the second iteration, frag is equal to two postings. And then on the final iteration frag is equal to the three postings. So then, we do all of our each. We leave the DOM alone. And then when we're finished we can say Jquery body.append(frag). Now we're getting the exact same effect. And again, for two or three postings, it really doesn't make a difference. But I want you to get in the habit of these best practices. Don't always manipulate the DOM on every iteration. The basic idea is within your each method or force statement, you want to do absolutely as little work as possible. Now in future lessons, we'll also take a look at different ways, such as document fragment. Or even using jQueries detach method, but this will do for now. See you later.