1 / 13

Return values Efficiency in Coding

Return values Efficiency in Coding. Learning Objectives. By the end of this lecture, you should be able to: Be able to apply an ‘object literal’ when setting multiple CSS properties Using an example, explain how an object literal can be an efficient way of coding

Télécharger la présentation

Return values Efficiency in Coding

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Return values Efficiency in Coding

  2. Learning Objectives By the end of this lecture, you should be able to: • Be able to apply an ‘object literal’ when setting multiple CSS properties • Using an example, explain how an object literal can be an efficient way of coding • Describe what is meant by being ‘efficient’ in your coding • Describe what is meant when a function ‘returns’ a value and what you can do with returned values • Describe what happens to a returned value if the programmer doesn’t write code to “do something with it” • Describe how to distinguish a command in JavaScript from a command in jQuery. • Describe a way that you can view your ‘rendered’ source code

  3. Object Literals Not surprisingly, we will often want to apply multiple styles to a single tag. For example, suppose you wanted to change the hyperlinks to all powerpoint files so that they were blue, at 75% size, and in Arial font. You could do this by applying 3 separate commands like so: $('a[href$=".ppt"]').css('color' , 'blue'); $('a[href$=".ppt"]').css('font-size' , '75%'); $('a[href$=".ppt"]').css('font-family' , 'Arial'); However, if you think about this, it is somewhat inefficient. (Programmers who are cognizant of issues such as efficiency are highly sought after and tend to make the most $$$! ) The reason this code is relatively inefficient is that the browser has to parse the entire page three separate times looking for that particualr selector (anchor tags that link to Powerpoint files). Wouldn’t it be nice if we could do all of them at once? Fortunately we can using a technique called ‘object literals’. The syntax for object literals may be a little confusing initially, but it is something you will get used to with a little bit of practice! An object literal is a list of property:value pairs. • It is different from the version shown above in that each property is separated from its value by a colon – not a coma. (Just like the original way you learned to set property/value pairs in plain old CSS!) • However, between each property:value pair, you DO place a comma. This is DIFFERENT from the way you change styles directly in CSS. In jQuery, you need a comma between each pair, NOT a semicolon. • The last property:value pair does NOT have a comma after it! • Finally, the entire object literal must be placed inside braces. {'color':'blue', 'font-size':'75%', 'font-family':'Arial' } Finally, this entire object literal is then provided as the argument to (i.e. inside the parentheses) the CSS function: $('a[href$=".ppt"]').css( {'color':'blue','font-size':'75%', 'font-family':'Arial'} ); *Incidentally, The 2nd edition of your book has an error in figure 4-5 on page 145 in which they use commas to separate property:value pairs!

  4. Pop-Quiz Can you find the bug or bugs in the following line of code? $('a.hover').css( {'color':'blue','font-size':'75%', 'font-family':'Arial', }; Answer: • There is a comma after the last property value pair. • There is also a second bug: We are missing the closing parenthesis ‘)’ of the css() function. It should appear immediately after the closing brace } . KEY POINT / IMPORTANT LESSON: When there is more than one bug, debugging can become a nightmare! That’s why you should do your coding in very small pieces and constantly save and refresh your browser. For example, in this case, I’d probably start with only ONE property:value pair in the object literal and make sure it works. Because there is much less code to that line, spotting a bug is MUCH MUCH easier! Once you’re confident that it works, add the next pair, do a quick test, and then another, etc. Incidentally, you might be tempted to think that the new line in the middle of the object literal could be a problem. However, using extra lines in a situation such as this is not only acceptable, it is frequently ideal as it makes the code that much easier to read.

  5. Performance and Efficiency We will periodically touch on issues relating to making your code as efficient as possible. This is a huge issue in programming. Programmers who are skilled at writing code that is maximized for speed and efficiency are extremely valued. Another example on improving performance touches on the object literal example. Recall that the performance benefit of the object literal is that the parser only has to look for the selector once instead of 3 separate times for each property:value pair. Well, this is, in fact, the second time we have discussed a technique for making our code more efficient. If you recall, jQuery has the ability to chain functions. In other words, if you want to apply multiple different functions to a single selector, you can improve the performance of your code by chaining them. Suppose you wanted to • Modify anchor tags to be in a different color • Have them start invisible • Fade in over 3 seconds You could write this as 3 separate jQuery commands. However, once again, the engine would have to parse your page 3 separate times searching for the ‘a’ selector. Instead, let’s just search for the selector once and each time we find that selector, apply all three different functions: $('a').css('color', 'red').hide().fadeIn(3000);

  6. Quick Review: Using the css() function to find the value of a property Recall that one use of the css() function is its ability to tell us the value of a css property. To do so, we simply pass the CSS property we are wondering about as the argument to the function, WITHOUT following the property by a comma and value. For example, if you wanted to find out which font your anchor tags are currently set to, you could write: $('a').css('font-family'); Suppose in a stylesheet somewhere, you had set the font of anchor tags to ‘Arial’. Then the function call above will returnthe string Arial . The idea of functions ‘returning’ a value is an extremely important one. Let’s discuss this concept now.

  7. Functions that “return” a value Suppose that in a stylesheet somewhere, you had styled ‘a’ tags as follows: a { font-family:Arial; color:red; font-size:125%;} Now suppose that in some other part of your document, inside a script tag somewhere, you have the following statement: $('a').css('font-family'); What do you think would happen if you were to type out this code in your page? The answer is… NOTHING! There would NOT be any errors generated, but at the same time, absolutely nothing would happen. And yet, this is an entirely legitimate statement. So, what is going on? The answer is that the job of some functions is not necessarily to make anything happen, but rather, is to return a piece of information. In the example above, the function call:$('a').css('font-family');will return the value of the font-family attribute that was applied to the anchor tag. Here it is in admittedly low-tech animation: • PROGRAMMER: Hey, computer, what is the value of the ‘font-family’ attribute for anchor tags? • COMPUTER: Let me check…. Here ya go: the value is: Arial So the computer program will simply return the String “Arial”. Question: What exactly did we (as the programmer) DO with that returned value? Answer: In the example just discussed, $('a').css('font-family'); we did NOTHING! Follow-Up Question: So, what happens to the returned value then? Answer: It simply… disappears!!

  8. Functions that “return” a value $('a').css('font-family'); //will return the String “Arial” When a function ‘returns’ a value, it is up to us as programmers to do something with that value. If we don’t do anything with the returned value, then that value simply goes away. Note: We do NOT get an error. In the code above, there is absolutely no problem. Rather, the returned value, the string “Arial” simply flies away and is gone forever. So what are some things that we programmers can do with a value that has been returned by a function? Answer: • Output it (e.g. to an alert box or document.write statement) • Store it in a variable • Pass the value to a different function • Etc “Arial”

  9. “Returning” a value, contd. Example of storing the returned value in a variable: var currentAnchorFont = $('a').css('font-family'); You could then use this variable anywhere such as, as the argument to an alert() function: alert('The current font for anchor tags is: ' + currentAnchorFont); Example of outputting a returned value: The Math.sqrt() function returns the square root of the argument (the value we pass inside the parentheses). In this example, we will simply output the returned value: document.write('The square root of 25 is: ' + Math.sqrt(25) );

  10. Pop-Quiz Recall that the Math.sqrt() function returns the square root of its argument. What would you expect to happen if you typed the following somewhere in a script? Math.sqrt(16); Answer: Nothing! The function will indeed return a 4.0. However, we did not do anything with that value! There is no bug in the code and no errors will be generated. However, because we didn’t do anything with the returned value, we ended up with a completely useless line of code! See file: returned_values.htm

  11. Mix ‘n’ Match JavaScript with jQuery Question: What would expect to happen if you typed: alert('hello'); Answer: You would see an alert box that simply says ‘hello’. Question: What about: $alert('hello'); Answer: This would be an error. The reason is that alert() is a JavaScript function. It is NOT a jQuery function. While you absolutely CAN mix and match JS with jQuery, the way we as programmers let the scripting engine know that you we are currently using a jQuery function is to precede the command with the dollar sign. This is why for functions like alert() , document.write() , Math.sqrt() – all of which are JavaScript (not jQuery) functions - we do NOT precede those particular function names by a dollar sign.

  12. How to view the “real” source code By now you have surely found the ‘View Source’ button on your browser. It allows you to view the source code of the page that is currently displayed. When you are doing basic, straight-forward HTML and CSS, this is not a problem. However, once you start using JS or any other scripting language to modify your code, things can get confusing. The reason is that the source displayed by ‘View Source’ may well be different once the scripting code has made modifications. In other words, the source you see is the code that was present before any scripts went to work. For example, suppose the user clicks a button that results in a series of ‘document.write’ statements that introduce a whole bunch of new HTML code into the page. The view source window will NOT show this new HTML code. All of the major browsers (IE9, Firefox, Safari, Chrome, Opera) typically offer some kind of ‘Rendered Source’ or ‘Rendered HTML’ window. This is a window that shows you the source present after the script has completed. • Accessing this window varies from browser to browser and from version to version. Therefore, I will not delve into a list of them here. However an online search should give quickly you the proper method for your preferred browser. • There are many choices here, but a popular one among developers is the ‘Firebug’ plug in for the Firefox browser. https://getfirebug.com/whatisfirebug At this point, you should install one of these on your browser.

  13. Viewing “Rendered” Source Code Using the modifying_attributes.htm page as an example, view the source of your page before clicking on the ‘Add Class’ button. You’ll see that no class has been applied to the random text paragraph. Then click on the ‘Add Class’ button and view the source again. You’ll note that the HTML source gives no indication that the class was applied. This is why you need a way of viewing the ‘rendered source”. A plugin such as Firebug (for Firefox) can show you the rendered source. All of the major browsers have plugins available that allow you to do things like view rendered source code, debug code, etc.

More Related