Secrets of JavaScript Ninja

This part of the book will set the stage for your JavaScript Ninja training.


Jhon Resig, Bear Bibeault


396 Pages

45603 Reads

54 Downloads

English

PDF Format

7.93 MB

Java Script

Download PDF format


  • Jhon Resig, Bear Bibeault   
  • 396 Pages   
  • 26 Feb 2015
  • Page - 1

    read more..

  • Page - 2

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 MEAP Edition Manning Early Access Program Secrets of the JavaScript Ninja version 11 Copyright 2012 Manning Publications For more information on this and other read more..

  • Page - 3

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 brief contents PART 1: PREPARING FOR TRAINING 1. Enter the ninja 2. Testing and debugging PART 2: APPRENTICE TRAINING 3. Functions are fundamental 4. Wielding functions 5. Closing in on read more..

  • Page - 4

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Part 1 Preparing for training This part of the book will set the stage for your JavaScript Ninja training. In chapter 1, you'll learn what we are trying to accomplish with this book, and read more..

  • Page - 5

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 1 Enter the ninja In this chapter:  A look at the purpose and structure of this book  Which libraries we’ll look at code from  What is “advanced” JavaScript programming? read more..

  • Page - 6

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 1.1 The JavaScript libraries we’ll be tapping The techniques and practices used to create modern JavaScript libraries will be the focus of our attention in this book. The primary library read more..

  • Page - 7

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 1.2 Understanding the JavaScript Language Many JavaScript coders, as they advance through their careers, may get to the point at which they're actively using the vast array of elements comprising read more..

  • Page - 8

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 animations. And a sound understanding of how regular expressions work allows us to simplify what would otherwise be quite complicated pieces of code. As another high point of our advanced tour read more..

  • Page - 9

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 An approach that we can employ is one loosely borrowed from an older Yahoo! Approach that they called Graded Browser Support. In this technique, we create a browser support matrix, that can serve read more..

  • Page - 10

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 1.2 shows a sample chart that represents information on browser usage (obtained from StatCounter for Audust 2012), and your authors’ personal opinions on cost of development, for the top read more..

  • Page - 11

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431  Even though Safari has a relatively low market share, it still deserves support, as its standard-compliant nature makes its cost small. (As a rule of thumb, if it works in Chrome, it’ll read more..

  • Page - 12

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 making process, taking into account factors such as the needs of the market, and other business concerns. But quantifying the costs versus benefits is a good starting point for making these read more..

  • Page - 13

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 If the value of variable a is not equal to one, the assertion fails and the somewhat overly- dramatic message is displayed. Note that the assert() function is not an innate feature of the read more..

  • Page - 14

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 2 Testing and debugging In this chapter: • Tools for Debugging JavaScript code • Techniques for generating tests • Building a test suite • How to test asynchronous operations read more..

  • Page - 15

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 2.1 Debugging Code Remember when debugging JavaScript meant using alert() to verify the value of variables? Well, the ability to debug JavaScript code has dramatically improved in the last few read more..

  • Page - 16

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 2.1 Logging lets us see the state of things in our code as it is running Older versions of Opera chose to go their own way when it comes to logging, implementing a proprietary read more..

  • Page - 17

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 then try to log a message using Opera’s proprietary method (#3). If both of those methods fail, we fall back to using old-fashioned alerts (#4). NOTE Within our method we used the read more..

  • Page - 18

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 2.2 Breakpoints allow us to halt execution at a specific line of code so we can take a gander at the state Note how the rightmost pane allows us to see the state within which read more..

  • Page - 19

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 browser implementers have come on board to create effective utilities for allowing debugging activities. Debugging code not only serves its primary and obvious purpose (detecting and fixing bugs), it read more..

  • Page - 20

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Let’s see an example of constructive testing. When creating reduced test cases, we can start with a few HTML files with minimum functionality already included in them. We might even have read more..

  • Page - 21

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 2.4: A screenshot of the JSBin web site in action With the tools and knowledge in place for figuring out how to create test cases, we can start to build test suites around these read more..

  • Page - 22

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 NOTE The raw results, should you be interested, can be found at actionURI(http://spreadsheets.google.com/pub?key=ry8NZN4-Ktao1Rcwae-9Ljw&output=html):http://spreadsheets.google.com/pub?key=ry8NZN4-Ktao1Rcwae-9Ljw&output=html. Figure 2.5 read more..

  • Page - 23

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 2.6 Most test-savvy developers favor a small handful of testing tools An interesting result, showing that there isn’t any one definitive preferred testing framework at this point. But even more read more..

  • Page - 24

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Obviously, according to the result depicted in figure 2.5, a number of people have come to this same conclusion and have written a large number of one-off frameworks to suite their own read more..

  • Page - 25

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 More information can be found aactionURI(http://www.jsunit.net/):t http://www.jsunit.net/ actionURI(http://www.jsunit.net/): UPDATE! New information too new to update this chapter in time for press! According to information on read more..

  • Page - 26

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 assert(false, "Fail!"); #2 }; </script> <style> #results read more..

  • Page - 27

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 2.5: An implementation of test grouping <html> <head> <title>Test Suite</title> <script> (function() { var results; read more..

  • Page - 28

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 holds a reference to the current test group (that way, the logging assertions are inserted correctly). Beyond simple testing of code, another important aspect of a testing framework is handling read more..

  • Page - 29

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 } } } this.assert = function assert(value, desc) { var li = document.createElement("li"); read more..

  • Page - 30

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431  pause() should be called from within a test function and tells the test suite to pause executing tests until the test group is done.  resume() unpauses the tests and starts read more..

  • Page - 31

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Part 2 Apprentice training Now that you are mentally prepared for training, as well as armed with the basic testing tools that we developed in the previous section, you are ready to read more..

  • Page - 32

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 3 Functions are fundamental In this chapter:  Why understanding functions is so crucial  How functions are first-class objects  How the browser invokes function  Declaring read more..

  • Page - 33

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 The fact that JavaScript treats functions as first-class objects is going to be important on a number of levels, but one significant advantage comes in the form of code terseness. To take a read more..

  • Page - 34

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 3.1 JavaScript is to Java as hamburger is to ham; both delicious, but not much in common except a name Hamburgers and ham are both foods that are meat products, just as JavaScript read more..

  • Page - 35

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Because most of our code will run as the result of a function invocation, we will see that having functions that are versatile and powerful constructs will give us a great deal of read more..

  • Page - 36

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431  Network events, such as responses to an Ajax request.  User events, such as mouse clicks, mouse moves, or key presses.  Timer events, such as when a timeout expires or an read more..

  • Page - 37

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 over. Under no circumstances are two handlers executing simultaneously in separate threads. Think of a line at the bank. Everyone gets into a single line and has to wait their turn to be read more..

  • Page - 38

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 page is going to execute as the result of an event (in other words as part of the “Process event” box). It’s important to note that whatever browser mechanism is putting the events read more..

  • Page - 39

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 3.3 Our useless function may not do much, but it shows that functions can be passed around and invoked at any later time That was really, really easy. And the reason is because of read more..

  • Page - 40

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 NOTE We’re not picking on Java – really, we’re not. It’s a fine language. We’re just using Java as the crutch here because it’s a good example of a language without read more..

  • Page - 41

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 The compare() method of the inline Comparator implementation is expected to return a negative number if the order of the passed values should be reversed, a positive number if not, and read more..

  • Page - 42

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 3.2 Declarations JavaScript functions are declared using a function literal that creates a function value in the same way that a numeric literal creates a numeric value. Remember that, as first read more..

  • Page - 43

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 assert(canFly.name === "", "canFly() has no name"); window.isDeadly = function(){ return true; }; #5 assert(typeof window.isDeadly === read more..

  • Page - 44

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 this reference as canFly() . In this respect, it is almost functionally equivalent (no pun intended) to declaring a named function named “canFly”, but not quite. One major difference: the function’s name read more..

  • Page - 45

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431  That window.isDeadly is defined as a function (#6). This is far from a complete test set of everything that we said about functions so far. How would you extend this test code to read more..

  • Page - 46

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 function within which they are declared, regardless of block nesting.  Named functions are in scope within the entire function within which they are declared, regardless of block nesting.  For read more..

  • Page - 47

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 3.2 shows the code with the repeated test as shown above removed so that we can see the forest for the trees (wherever the test code has been removed, we show the comment /* test read more..

  • Page - 48

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #2 Runs our test block inside function outer() but before anything else has been declared. The outer() function is still in scope as is the inner() function which is defined within outer() read more..

  • Page - 49

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 3.5 Running our scope tests clearly shows where the declared items are in scope, and where they are not 46 Licensed to Matt a Ruby <mattaruby@hotmail.com> read more..

  • Page - 50

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 As expected, there are many failures as not all of the items are in scope at every position where we placed the block of tests. Of particular note, see how the declaration of inner() read more..

  • Page - 51

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 PONDER THIS Now that you understand a bit about scope, you should be able to answer the following question: rather than cutting and pasting the block of tests over and over again, why did read more..

  • Page - 52

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 function whatever(a,b,c) { … } If we were to call it with whatever(1,2,3,4,5) , the arguments, 1, 2, and 3 would be assigned to a , b , and c , respectively. Arguments 4 and 5 are read more..

  • Page - 53

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 ways that a function can be invoked. And as it turns out, what the this parameter points to is not, as in Java, defined by how the function is declared, but by how it is invoked! read more..

  • Page - 54

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 o.whatever = function(){}; o.whatever(); OK, so what? The function is called a “method” in this case, but what makes that interesting or useful? Well, if you come from any object-oriented background, read more..

  • Page - 55

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #3 Creates a reference to the same function in variable sneak. #4 Invokes the function using the sneak variable. Even though we’ve used a variable, the function is still invoked as a read more..

  • Page - 56

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Then we create a reference to the function in a variable named sneak (#3). Note that this does not create a second instance of the function; it merely creates a reference to the read more..

  • Page - 57

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 3.3.4 Invocation as a constructor There’s nothing special about a function that’s going to be used as a constructor; constructor functions are declared just like any other function. The read more..

  • Page - 58

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 </script> #1 Defines the constructor which creates a skulk property on whatever object is the function context. The method once again returns the function context so that we can test read more..

  • Page - 59

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 CODING CONSIDERATIONS FOR FUNCTIONS The intent of constructors is to initialize the new object that will be created by the function invocation to initial conditions. And while such functions can be read more..

  • Page - 60

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 That’s usually exactly what we want; but not always. For example, in the case of a method, we might want to force the function context to be the owning object of the method and not the read more..

  • Page - 61

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 3.9 The apply and call methods let us set the function context to any object of our choosing In this example, we set up a function named juggle() (#1), in which we define juggling read more..

  • Page - 62

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 common to pass the array to a method and use a for-loop to iterate over every entry, performing the operation on each entry. function(collection) { for (var n = 0; n < collection.length; read more..

  • Page - 63

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #4 Tests the function Our iteration function sports a simple signature that expects the array of objects to be iterated over as the first argument, and a callback function as the second read more..

  • Page - 64

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Another exercise you could task yourself with: enhance the function so that the page author can also pass an arbitrary number of arguments to the callback in addition to the iteration index. read more..

  • Page - 65

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 lengths. o Unassigned parameters evaluate as undefined . o Extra arguments are simply not bound to parameter names.  Each function invocation is passed two implicit parameters: o arguments , a read more..

  • Page - 66

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 4 Wielding functions In this chapter:  Why anonymous functions are so important  Recursion in functions  The ways that functions can be referenced for invocation  How to read more..

  • Page - 67

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 we’re striving for JavaScript ninja-hood. They are an important and logical feature for a language that takes a great deal of inspiration from functional languages such as Scheme. Anonymous read more..

  • Page - 68

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 But why bother to create the separate top-level function with a name when it’s not really needed? Next, we declare an anonymous function as a property of an object (#2), which we know from read more..

  • Page - 69

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 We’re going to see anonymous functions a lot in the code throughout the rest of this book because prowess with JavaScript directly relies upon using it as a functional language. As such we’re read more..

  • Page - 70

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 if (text.length <= 1) return true; if (text.charAt(0) != text.charAt(text.length - 1)) return false; return isPalindrome(text.substr(1,text.length - 2)); } Note that the new definition, and our read more..

  • Page - 71

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 The function clearly calls itself, so the first criterion is satisfied. And because the value of parameter n decreases with each iteration, it will sooner or later reach a value of one read more..

  • Page - 72

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 That’s all fine as it stands, but because we’re relying upon an indirect reference to the function – namely, the chirp property of ninja – we could be standing on thin ice. And read more..

  • Page - 73

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 </script> #1 Creates a chirp() method on samurai by referencing the existing method of the same name on ninja. Why write the code twice when we already have an implementation? #2 read more..

  • Page - 74

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 4.3 The two objects have a reference to the same function, but the function refers to itself through only one of the objects, Thin ice! At that point, there really isn’t any problem read more..

  • Page - 75

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 uses the ninja.chirp reference to call itself, regardless of whether the function is invoked as a method of ninja or of samurai . So what happens if ninja were to go away, leaving samurai read more..

  • Page - 76

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 functions. But as it turns out, there’s nothing wrong with giving any function literal a name, even those that are declared as callbacks or methods. No longer anonymous, these functions are read more..

  • Page - 77

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 ninja(); #3 assert(typeof myNinja == "undefined", read more..

  • Page - 78

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 }; assert(ninja.chirp(3) == "chirp-chirp-chirp", #2 "arguments.callee is the function itself."); </script> #1 References the arguments.callee property As we read more..

  • Page - 79

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Another capability that may have surprised a few people is that, just like any other object, we can attach properties to a function, as in: var obj = {}; var fn = function(){}; obj.prop = read more..

  • Page - 80

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #1 Keeps track of the next available id to be assigned. #2 Creates an object to serve as a cache, in which we will store the functions. #3 Adds functions to the cache, but read more..

  • Page - 81

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Another useful trick that we can pull out of our sleeves using function properties is giving a function the ability to modify itself. This technique could be used to remember previously read more..

  • Page - 82

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Within the isPrime() function, we start by checking to see if the answers property that we’ll use as a cache has been created, and if not, we create it (#1). The creation of this read more..

  • Page - 83

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Table 4.1: All time in ms, for 100,000 iterations, in a copy of Chrome 17 Average Min Max Runs non-cached version 16.7 18 19 10 cached version 3.2 3 4 10 Even these simple read more..

  • Page - 84

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 gather: function(id){ #3 this.add(document.getElementById(id)); } }; read more..

  • Page - 85

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 4.4 Variable-length argument lists JavaScript, as a whole, is very flexible in what it can do, and much of that flexibility defines the language as we know it today. One of these flexible and read more..

  • Page - 86

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Let’s see how we can use that ability to our advantage in defining our array-inspecting functions. Consider listing 4.11. Listing 4.11: Generic min and max functions for arrays read more..

  • Page - 87

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 DETECTING AND TRAVERSING ARGUMENTS In other more pure object-oriented languages, method overloading is usually effected by declaring distinct implementations of methods of the same name but differing read more..

  • Page - 88

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 TIP If no argument that corresponds to a named parameter is passed, the named parameter can be checked for this situation with: paramname === undefined . So we can get at the first read more..

  • Page - 89

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 the second element in the arguments list to Math.max() , we’ll use the slice() method of arrays to create an array that omits the first element. So, we go ahead and write up the read more..

  • Page - 90

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 true array. But either of these approaches seems ham-handed and redundant when we know that Array already has the functionality we seek. So before we resort to copying the data or read more..

  • Page - 91

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 named parameters with which the function was declared. Thus, if we declare a function with a single formal parameter, its length property will have a value of 1. Examine the following code: read more..

  • Page - 92

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 addMethod(ninja,'whatever',function(){ /* do something */ }); addMethod(ninja,'whatever',function(a){ /* do something else */ }); addMethod(ninja,'whatever',function(a,b){ /* yet something else */ }); Here, we create the object and read more..

  • Page - 93

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 (#2). Failing that, it will call the function stored in old (#3), which as you will recall, will check for zero parameters, and call the version of fn with zero parameters. On the third read more..

  • Page - 94

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 </script> #1 Declares an object to serve as the base, pre-loaded with some test data. #2 Binds a no-argument method to the base object. #3 Binds a single-argument method to the base read more..

  • Page - 95

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 This technique is especially nifty because all of these bound functions aren't actually stored in any typical data structure. Rather, they're all saved as references within closures. Again, we'll read more..

  • Page - 96

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 There are a lot of possible avenues for exploration here; unfortunately almost all of the techniques end up in a dead-end. For example, we know that functions have an apply() and call() read more..

  • Page - 97

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 4.6 Summary In this chapter we took the knowledge that we gained in chapter 3, and wielded it to solve a number of problems we’re likely to find in applications. In particular:  read more..

  • Page - 98

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 5 Closing in on closures In this chapter: • What are closures and how do they work? • Using closures to simplify development • Improving performance using closures • Solving common scoping read more..

  • Page - 99

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 That may seem rather intuitive until you remember that a declared function can be called at any later time, even after the scope in which it was declared has gone away. This concept is read more..

  • Page - 100

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 You’ve likely written code such as this hundreds of times without realizing that you were creating a closure! Not impressed? I guess that’s not surprising. Because both of the outer value and read more..

  • Page - 101

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 function executes, the scope inside the outer function is long gone and not visible at the point at which we’re invoking the function through later . So we could very well expect the assert read more..

  • Page - 102

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 5.3 Like a protective bubble, the closure for innerFunction keeps the variables in the function’s scope from being garbage collected as long as the function exists. Let’s augment that example read more..

  • Page - 103

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 later = innerFunction; } assert(!tooLate,"Outer can't see the ronin"); #3 var tooLate = 'ronin'; read more..

  • Page - 104

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 When the tests inside the inner function execute (#2), we can see the display of figure 5.4. This shows three more interesting concepts regarding closures: 1. Function parameters are included read more..

  • Page - 105

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 }; #4 } var ninja = new Ninja(); read more..

  • Page - 106

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 able to make uncontrolled changes to the value of the variable, just as if it were a private variable in a fully object-oriented language. This situation is depicted in figure 5.5. Figure read more..

  • Page - 107

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 For now, let’s focus on another common use of closures. 5.2.2 Callbacks and timers Another one of the most common areas in which we can use closures is when dealing with callbacks or read more..

  • Page - 108

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 up a reference to the <div> element each time, but we want to be stingy regarding performance so we’ll just look it up once, and store it away in a variable named elem$ (#2) read more..

  • Page - 109

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #4 Creates and starts an interval timer given a callback function that will be invoked every 10 milliseconds. For 100 ticks, it will adjust the position of the element. #5 After 100 ticks, read more..

  • Page - 110

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 These three variables (the reference to the DOM element (#2), the tick counter (#3), and the timer reference (#4)) all must be maintained across the steps of the animation. And, we need read more..

  • Page - 111

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 5.7 By creating multiple closures, we can do many things at once! Without closures, doing multiple things at once, be it event handling, animations or even Ajax requests, would be incredibly read more..

  • Page - 112

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 executes. In other words, the closure isn’t simply a snapshot of the state of the scope at the time of creation, but an active encapsulation of that state that can be modified as long as read more..

  • Page - 113

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 serve as an event handler (#3) that will fire when the button is clicked in order to record the click. Within the method, which we establish as a click handler for the button (#5), we set read more..

  • Page - 114

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 We can force a particular function invocation to always have a desired context using a mix of anonymous functions, .apply() , and closures. Take a look at the code of listing 5.8, which updates read more..

  • Page - 115

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 5.9 The anonymous function serves as an event-handling proxy for the “real” handler, which is identified though parameters bound to the closure This particular implementation of a binding function read more..

  • Page - 116

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 5.9: An example of the function binding code used in the Prototype library Function.prototype.bind = function(){ #1 var fn = this, read more..

  • Page - 117

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 This sort of proxy function – one that stands in for another function and calls that function when executed – is exactly the technique we used in the previous section to “bind” specific read more..

  • Page - 118

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 5.10 Our CSV-splitting function works! Now all we have to do is implement it. With all that in mind, let's look at how a partial/curry method is (more or less) implemented in the read more..

  • Page - 119

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Implementations of this style of partial function application have existed in other languages but Oliver Steele was one of the first to demonstrate it with his Functional.js read more..

  • Page - 120

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Up to this point, we’ve used closures to reduce the complexity of our code, demonstrating some of the power that functional JavaScript programming has to offer. Now let’s continue to explore read more..

  • Page - 121

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #1 We’re going to store a cache of values in values. Here we check to see if we’ve already created it, and do so if not. #2 When we get called with a key, we check to read more..

  • Page - 122

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 5.14: A technique for memorizing functions using closures <script type="text/javascript"> Function.prototype.memoized = function(key){ this._values = this._values || {}; return read more..

  • Page - 123

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 construct a temporary function whose results won't be memorized. We take this anonymous, prime-figuring function and memoize it immediately, giving us a new function, which is assigned to the isPrime read more..

  • Page - 124

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 original(elem, attr); }); } #1 Defines a generic wrapping function taking as parameters: an object whose method is to be wrapped, the name of the object method to be read more..

  • Page - 125

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 5.11 The anonymous wrapping function has access to the original function, as well as the passed wrapper function, via the closure The result of all this is a reusable wrap() function read more..

  • Page - 126

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 parentheses, may seem a little strange, let's deconstruct what's going on within it step by step. First, let’s ignore the contents of the first set of parentheses, and examine the construct: read more..

  • Page - 127

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Additionally, since we're dealing with a function that can have a closure just like any other, we also have access to all outside variables and parameters that are in the same scope as the read more..

  • Page - 128

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 expression, the returned value is passed to the addEventListener method. However, the inner function that we created still gets the necessary numClicks variable via its closure. This technique is read more..

  • Page - 129

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 })(jQuery); #4 </script> </body> #1 We redefine $ to be something other than jQuery. #2 The read more..

  • Page - 130

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 href: v._getAttr, src: v._getAttr, type: v._getAttr, action: v._getAttrNode, disabled: v._flag, checked: read more..

  • Page - 131

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Our intention is that clicking each <div> element will show its ordinal value. But when we load the page and click on “DIV 0”, we see the display of figure 5.12. Figure 5.12: read more..

  • Page - 132

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 })(i); </script> By using an immediate function as the body of the for loop (replacing the previous block) we enforce the correct ordinal value for the handlers by passing that read more..

  • Page - 133

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 principle, completely enclosing all of its functionality and only introducing the variables it needs, like jQuery , as shown here: (function(){ var jQuery = window.jQuery = function(){ // read more..

  • Page - 134

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 We started with the basics, looking at how closures are implemented, and then how to use them within an application. We looked at a number of cases where closures were particularly useful, read more..

  • Page - 135

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 6 Object-orientation with prototypes In this chapter:  Using functions as constructors  Exploring prototypes  Extending objects with prototypes  Avoiding common gotchas  Building classes read more..

  • Page - 136

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 chapter 3 that using the new keyword to invoke a function calls the function as a constructor with a newly instantiated and empty object as its context. As object instantiation is a large read more..

  • Page - 137

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 assert(ninja2 && ninja2.swingSword && ninja2.swingSword(), "Instance exists and method is callable." ); </script> #1 Defines a function read more..

  • Page - 138

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 6.1 A prototype lets us predefine properties, including methods, to be automatically injected into new object instances Note that we didn’t do anything overt in the constructor to make this read more..

  • Page - 139

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 return this.swung; }; var ninja = new Ninja(); #4 assert(ninja.swingSword(), "Called the instance method, not the read more..

  • Page - 140

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 constructor body overrides the prototype value. But as it turns out, we can observe some behaviors that don’t make sense if this was really what was going on. If we were to assume that read more..

  • Page - 141

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 6.2: Our test proves that prototype changes are applied live! So clearly there’s more to all this than a simple copying of properties when the object is created. What’s really read more..

  • Page - 142

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 6.3 Objects are tied to their constructors, which are in turn tied to prototypes for objects created by the constructor Each object in JavaScript has an implicit property named constructor that read more..

  • Page - 143

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 6.4 Inspecting the structure of an object reveals the path to its prototype When we type the reference ninja.constructor into the console, we see that it references the Ninja() function as read more..

  • Page - 144

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 6.5 Property references are first looked for in the object itself; if not found, the constructor’s prototype is inspected In the figure, an object reference by variable ninja has read more..

  • Page - 145

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 6.4: Further observing the behavior of changes to the prototype <script type="text/javascript"> function Ninja(){ this.swung = true; this.swingSword = function(){ read more..

  • Page - 146

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 6.5: Examining the type of an instance and its constructor <script type="text/javascript"> function Ninja(){} var ninja = new Ninja(); assert(typeof ninja == "object", read more..

  • Page - 147

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #2 Proves the new object’s Ninja-ness. #3 But just because on was created from the other, they are not the same object but two distinct instances. We define a constructor and create read more..

  • Page - 148

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 As the prototype of a function is just an object, there are multiple ways of copying functionality (such as properties or methods) to effect inheritance. In this code, we define a Person (#1), read more..

  • Page - 149

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 What we really want to achieve is a prototype chain so that a Ninja can be a Person, and a Person can be a Mammal, and a Mammal can be an Animal, and so on, all the way to read more..

  • Page - 150

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 6.7: Our ninja is a Person! Let the dancing begin. The very important implications of this are that when we perform an instanceof operation we can determine if the function inherits read more..

  • Page - 151

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 6.8: The prototype chain through which properties are reconciled for the dancing ninja It's important to note that our object also has properties that are inherited from the Object prototype. read more..

  • Page - 152

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 be an incredibly powerful feature of the language. Using it, we can extend the functionality of the language itself, introducing new or missing pieces of the language. NOTE As with most read more..

  • Page - 153

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 thing if so. This makes the code future-compatible, as when it executes in an environment where the method is defined, it will defer to the native method. If we determine that the method read more..

  • Page - 154

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 document.getElementById("b").remove(); #3 assert(!document.getElementById("a"),"a is gone."); assert(!document.getElementById("b"),"b is gone too."); </script> #1 Adds a read more..

  • Page - 155

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 It’s best to tread lightly should you choose to employ this technique. Adding methods is usually fairly benign, but changing the way that existing code acts should be considered very carefully read more..

  • Page - 156

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 6.9: Whoa! We screwed up a fundamental assumption of objects! What went wrong, of course, is that in adding the keys() method to Object, we introduced another property that will appear read more..

  • Page - 157

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 var obj = { a: 1, b: 2, c: 3 }; assert(obj.keys().length == 3, #2 "There are three properties in this object."); </script> read more..

  • Page - 158

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Here we define a new add() method on Number (#1) that will take the argument, add it to the number’s value, and return the result. Then we test the new method using various number read more..

  • Page - 159

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 In general, it’s best to simply avoid mucking around with the Number prototype. Now let’s look at some issues we can encounter when we subclass, rather than augment, native objects. 6.2.3 read more..

  • Page - 160

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 var methods = ['push', 'pop', 'shift', 'unshift', 'slice', 'splice', 'join']; for (var i = 0; i < methods.length; i++) (function(name) { MyArray.prototype[ name ] = function() { read more..

  • Page - 161

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 assert(user, "User instantiated"); #3 assert(user.name == "Ichigo Kurosaki", #4 "User name correctly assigned"); read more..

  • Page - 162

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 of a new object. A novice user might easily fall into this trap, trying to call the function without the operator, causing bafflingly unexpected results (e.g. user would be undefined). NOTE read more..

  • Page - 163

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 To find out why, look at the code of the constructor. When called as a constructor, the context of the function invocation is the newly allocated object. But what is the context when called as read more..

  • Page - 164

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 If we weren’t ninjas, we might just throw an Error telling the user to do it right next time. But we’re better than that. Let’s see if we can just fix the problem for them. Consider read more..

  • Page - 165

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 OK, enough of the problems. Let’s take a look at how we use these new-found powers to write more class-like code. 6.3 Writing class-like code While it’s great that JavaScript lets us use a read more..

  • Page - 166

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 return true; } }); var person = new Person(true); #4 assert(person.dance(), read more..

  • Page - 167

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 code – but we’re all here to become ninjas, and this is Master Ninja Territory. So don’t feel bad if it takes a while for you to grok it. In fact, to make it a bit easier read more..

  • Page - 168

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 })(); #1 This gnarly regular expression test determines if functions can be serialized. Read on to see what all that means. #2 Adds the subClass() method to Object. #3 Instantiates the superclass read more..

  • Page - 169

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 supported, so we substitute a pattern that matches anything in browsers that don’t allow us to serialize functions. We’ll be using this result later on, but by doing the check now, we read more..

  • Page - 170

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 accessible from within a subclassed method, and that references the original method in the superclass. For example, recall from listing 6.20, when we wanted to call a superclass' constructor, we read more..

  • Page - 171

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 2. Is the superclass property a function? 3. Does the subclass function contain a reference to _super() ? Only if all three clauses are true do we need to do anything other than read more..

  • Page - 172

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 In this chapter, we looked at how using the prototype property of functions allows us to bring object-orientation to JavaScript code. We started by examining exactly what prototype is, and what read more..

  • Page - 173

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 7 Wrangling regular expressions Covered in this chapter:  A refresher on regular expressions  Compiling regular expressions  Capturing with regular expressions  Frequently-encountered idioms read more..

  • Page - 174

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 TIP Getting fluent with regular expressions requires a lot of practice. You might find a site such as http://jsbin.com handy to play around with the examples quickly. Another useful site expressly read more..

  • Page - 175

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Even so, would anyone consider this solution elegant? Surely, more elegant than the brute-force, non-iterative approach would be, but it still seems like an awful lot of code for such a simple check. read more..

  • Page - 176

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 The literal syntax is preferred when the regex is known at development time, and the constructor approach used when the regex is constructed at run-time by building it up dynamically in a read more..

  • Page - 177

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 MATCHING FROM A CLASS OF CHARACTERS Many times, we won’t want to match a specific literal character, but from a finite set of characters. We can specify this with the set operator (also called read more..

  • Page - 178

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 REPEATED OCCURRENCES If we wanted to specify that we desire to match a series of 4 ‘a’ characters, we might express that with /aaaa/ , but what if we wanted to match any number of read more..

  • Page - 179

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Table 7.1: Predefined character class and character terms Predefined term Matches \t Horizontal tab \b Backspace \v Vertical tab \f Form feed \r Carriage return \n New line \cA : \cZ read more..

  • Page - 180

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 When a part of a regex is grouped with parentheses, it serves double duty, also creating what’s known as a capture. There’s a lot to captures, and we’ll be discussing them in more depth read more..

  • Page - 181

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 conversion must occur every time a regular expression is created (discounting any internal optimizations performed by the browser). Frequently browsers are smart enough to determine when identical regular read more..

  • Page - 182

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 7.3: Compiling a run-time regular expression for later use <div class="samurai ninja"></div> #1 <div class="ninja samurai"></div> read more..

  • Page - 183

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 the incoming className argument) we can realize major performance savings by handling the expression in this manner. The regex itself matches either of the beginning of the string or a read more..

  • Page - 184

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 "" : elem.style.opacity; } window.onload = function() { assert( getOpacity(document.getElementById("opacity")) == "0.5", "The read more..

  • Page - 185

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 first match, the array returned contains the global matches; captures within each match are not returned in this case. We can see this in action in the code and tests of listing 7.5. read more..

  • Page - 186

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 assert(num == 6, "3 opening and 3 closing tags found."); </script> #1 Repeatedly calls exec() In this example, we repeatedly call the exec() method (#1) which retains state from its previous read more..

  • Page - 187

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 of course, that there aren't any embedded tags of the same name within the current tag; so this is hardly an exhaustive example of tag matching.) Additionally, there's a way to get capture read more..

  • Page - 188

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 parenthesis to indicate a non-capture grouping. This is known as a passive sub- expression. So, changing our regular expression to: var pattern = /((?:ninja-)+)sword/; causes only the outer set of read more..

  • Page - 189

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 When the replacement value (second argument) is a function, it is invoked for each match found (remember a global search will match all instances of the pattern in the source string) with a read more..

  • Page - 190

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 foo=1&foo=2&blah=a&blah=b&foo=3 into one that looks like this: foo=1,2,3&blah=a,b" A solution using regular expressions and replace() could results in some especially terse code as shown read more..

  • Page - 191

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Note how we simply return the empty string because we really don’t care what substitutions happen to the source string – we’re just using the side effects rather than the actual read more..

  • Page - 192

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 details aactionURI(http://blog.stevenlevithan.com/archives/faster-trim-javascript):t http://blog.stevenlevithan.com/archives/faster-trim-javascript. It's important to note, however, that in his test cases he works against an incredibly large read more..

  • Page - 193

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Table 7.2: Performance comparison of three trim() implementations Short string Document listing 7.11 8.7 2075.8 listing 7.12 8.5 3706.7 listing 7.13 13.8 169.4 This comparison makes it easy to read more..

  • Page - 194

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 In the first test (#2) we verify that newlines, indeed, are not matched by the . operator. Well, ninjas will not be denied, so in the next test (#3) we get our way with an alternate regex, read more..

  • Page - 195

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 example is to show how to match Unicode characters in general. If you have a specific range of characters that you want to match, you can use the lesson of this example to add whatever read more..

  • Page - 196

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 developer should feel comfortable in tackling a challenging piece of code that could benefit from regular expressions. During the course of this chapter, we first took a whirlwind tour through read more..

  • Page - 197

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 8 Taming threads and timers In this chapter:  How JavaScript handles threading  An examination of timer execution  Processing large tasks using timers  Managing animations with read more..

  • Page - 198

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 This chapter will take a look at how this all works. 8.1 How timers and threading work Due to their sheer usefulness, it's important to understand how timers work at a fundamental read more..

  • Page - 199

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 An important concept that needs to be understood with regard to JavaScript timers is that the timer delay is not guaranteed. The reason for this has a great deal to do with the nature of read more..

  • Page - 200

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 amount of time they are running. For example, the first block of mainline JavaScript code executes for approximately 18ms, the mouse click block for approximately 10ms, and so on. Because read more..

  • Page - 201

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 expires at the 40 ms mark, causing the invocation of the interval handler to be queued. When the first invocation finishes at 42 ms, this queued handler executes. This time, the handler read more..

  • Page - 202

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431  JavaScript engines execute only a single thread at a time, forcing asynchronous events to queue up, awaiting execution.  If a timer is blocked from immediately executing, it will be read more..

  • Page - 203

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 8.2: Interval timer performance measured on OS X browsers shows that some browsers get pretty close to 1 ms granularity 200 Licensed to Matt a Ruby <mattaruby@hotmail.com> read more..

  • Page - 204

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 8.3 Interval timer performance as measured on Windows browsers is equally all over the place These charts plot the number of times, out of the 100 tick run, that each interval value read more..

  • Page - 205

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Under OS X, for Firefox we found that the average value was around 4 ms, almost always with some much longer outlying results, such as the single interval that took 22 ms. Chrome was read more..

  • Page - 206

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 8.3 Dealing with computationally-expensive processing The single-threaded nature of JavaScript is probably the largest “gotcha” in complex JavaScript application development. While JavaScript is busy executing, user read more..

  • Page - 207

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 tbody.appendChild(tr); #E } </script> #A Finds the <tbody> element that we’re going to create a read more..

  • Page - 208

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 In this modification to our example we've broken up our lengthy operation into 4 smaller operations, each creating 35,000 DOM nodes. These smaller operations are much less likely to interrupt the read more..

  • Page - 209

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 8.4: A web-based schedule generation application with client-side computation These operations were quite expensive (running through thousands of permutations in order to find correct results). The read more..

  • Page - 210

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 interfering with the normal operation of the browser. We saw previously that, by making sure that no one timer handler invocation performs excessively lengthy operations that we can prevent our code read more..

  • Page - 211

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 } timers.timerID = setTimeout(runNext, 0); } })(); }, stop: function() { read more..

  • Page - 212

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 }); timers.start(); We get a reference to the element, add a handler that moves the element horizontally, another handler that moves it vertically, and start the whole shebang. The result, after read more..

  • Page - 213

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 As we saw in test examples in the previous chapters, we can easily just run the tests as we come to them, and most of the time, this is fine. However once we need to do read more..

  • Page - 214

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 the previous example but handles a queue of data instead. Its sole purpose is to dequeue a function and execute it if there is one waiting. Otherwise, it completely stops the interval read more..

  • Page - 215

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Part 3 Ninja training Now that you have snatched the pebble and graduated from apprenticeship, this part of the book takes the fundamentals you learned and teaches you how to survive read more..

  • Page - 216

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 9 Ninja alchemy: Run-time code evaluation What’s in this chapter:  How run-time code evaluation works  Different techniques for evaluating code  Using evaluation in applications  read more..

  • Page - 217

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 9.1 Code evaluation mechanisms Within JavaScript there are a number of different mechanisms for evaluating code. Each has its own advantages and disadvantages and which to use should be chosen read more..

  • Page - 218

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 assert(window.ninja === 5, #5 "the global scope was unaffected"); #5 read more..

  • Page - 219

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 that the variable exists with the expected value is conducted. But once again, that’s not quite enough. Is ninja evaluating to 6 because we created a new variable in the local scope? Or read more..

  • Page - 220

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 As an exercise, make a copy of listing-9.2.html , remove the parentheses, and load the file. See how far you get! If you ran this test under Internet Explorer 8 or earlier, you may have gotten read more..

  • Page - 221

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 9.1.3 Evaluation with timers Another way that we can cause strings of code to be evaluated, and in this case asynchronously, is through the user of timers. Normally, as we saw in chapter read more..

  • Page - 222

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 9.2 The code evaluated inside the immediate function results in a variable created inside that scope and invisible to other scopes 219 Licensed to Matt a Ruby <mattaruby@hotmail.com> read more..

  • Page - 223

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 A naïve solution would be to change the code to be evaluated to: eval("window.test = 5;"); While this would cause the variable to be defined in the global scope, it does not read more..

  • Page - 224

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 </script> #1 Defines a global eval function #2 Creates a script node #3 Attaches it to the DOM #4 Blows it away The code for this is surprisingly simple. For use in place of read more..

  • Page - 225

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 9.1.5 Safe code evaluation One question that frequently arises with respect to code evaluation, concerns the safe execution of JavaScript code. In other words: is it possible to safely execute untrusted read more..

  • Page - 226

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 becoming compromised. We're certainly going to see a lot of work in this realm and Google Caja may lead the way. OK, so now we know a number of ways to take a string and read more..

  • Page - 227

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 9.5: A function for finding the argument names of a function <script type="text/javascript"> function argumentNames(fn) { var found = /^[\s\(]*function[^(]*\(\s*([^)]*?)\s*\)/ #1 read more..

  • Page - 228

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 9.3 We can use function decompilation to do fancy things such as inferring the names of arguments to a function There’s an important point to take into consideration when working with read more..

  • Page - 229

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 9.3 Code evaluation in action We saw in section 9.1 that there are a number of ways in which code evaluation can be performed. We can use this ability for both interesting and practical read more..

  • Page - 230

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Some important pre-processing that Mr. Crockford’s function performs prior to the actual evaluation include:  Guarding against certain Unicode characters that can cause problems in some browsers.  read more..

  • Page - 231

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 "var Base=base2.Base;var Package=base2.Package;" + "var Abstract=base2.Abstract;var Module=base2.Module;" + "var Enumerable=base2.Enumerable;var Map=base2.Map;" + read more..

  • Page - 232

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e( parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29): c.toString(36))};if(!''.replace(/^/,String)){while(c--) r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}]; read more..

  • Page - 233

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 However, performance may not always be your number one focus. Even with the additional overhead, the Packer can be a valuable tool if obfuscation is what you are after. Unlike server-side code, read more..

  • Page - 234

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Note the methods: describe() , it() and expect() , none of which exist in the global scope. To make this code possible, Screw.Unit rewrites this code on the fly to wrap all the functions read more..

  • Page - 235

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 NOTE Remember the memoization example of section 5.5? That was actually a good example of applying AOP in JavaScript. So you’ve already done it without even knowing it! We've previously read more..

  • Page - 236

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 .tmpl() method to provide run-time templates. This technique could be used for such varying purposes as: executing scripts on user interaction, or when the DOM is ready to be manipulated, or read more..

  • Page - 237

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 extendClass(__self,arguments,Spin); this.dim = 0; extendClass(this, Spin); addMethod(this, 'display', function() { noStroke(); pushMatrix(); translate(x, y); angle += speed; read more..

  • Page - 238

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 to providing a thin layer over the JavaScript language, Objective-J allows JavaScript code to be mixed in with the Objective-C code. An example is shown here: // DocumentController.j // Editor // // read more..

  • Page - 239

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Objective-C syntax, without disrupting the existing JavaScript. The result is a string of JavaScript code, which is evaluated using run-time evaluation. While this implementation has less far-reaching read more..

  • Page - 240

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 10 With statements Covered in this chapter:  Why the with statement is controversial  How with statements work  Code simplification with with  Tricky with gotchas  Templating read more..

  • Page - 241

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Douglas Crockford, April 2006 The full blog post is available at http://yuiblog.com/blog/2006/04/11/with-statement- considered-harmful/ Mr. Crockford was not alone. Many JavaScript editors and IDEs (Integrated read more..

  • Page - 242

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 "context isn't changed; keeps its original value"); } assert(use === "other", #5 read more..

  • Page - 243

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Our testing continues outside the scope of the with statement (#4) verifying that references to use refer to the top-level variable, and that the isSharp property is no longer available. Note read more..

  • Page - 244

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 initial value of true to false . We explicitly test the property (#3) and peeking ahead to figure 10.2, we see that this test passes. This proves that we can use un-prefixed references to read more..

  • Page - 245

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 rather than modifying the intended existing property on the with scope’s object. Of course, this is something we need to generally be aware of, so we'll just need to carefully test our read more..

  • Page - 246

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 assert(true,"With (without access): " + elapsed); </script> #1 Sets up variables #2 Tests without with #3 Tests referencing #4 Tests assignments #5 tests with no access For these performance read more..

  • Page - 247

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 the with scope’s object was referenced or assigned, but look at the times in the right-most column whose test performed no access to the object at all. The mere fact that the code was read more..

  • Page - 248

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 backgroundImage = "url(http://ie7-js.googlecode.com/svn/trunk/lib/blank.gif)"; backgroundAttachment = "fixed"; } In this snippet, base2 again uses with as a simple means of not having to read more..

  • Page - 249

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Now let’s see another use to which we might put the with statement. 10.3 Importing name-spaced code As previously shown, one of the most common uses for the with statement is to simplify read more..

  • Page - 250

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 assertEqual(0, slider.value); slider.dispose(); }}, // ... }); Note the use of with(this) in the above test run. The instance variable contains all the assertion methods read more..

  • Page - 251

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 <script type="text/javascript"> var colorsArray = ['red', 'green', 'blue', 'orange']; var items = []; for (var i = 0; i < 10000; i++) { items.push( read more..

  • Page - 252

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 return data ? fn( data ) : fn; #E }; })(); assert( tmpl("Hello, <%= name %>!", {name: "world"}) == "Hello, world!", "Do read more..

  • Page - 253

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 10.6 Summary The glaringly obvious point that we learned from this chapter is that the primary goal of the with statement is to simplify complex code by allowing properties of an object read more..

  • Page - 254

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 11 Developing cross-browser strategies In this chapter: • Strategies for developing reusable, cross-browser JavaScript code • Analyzing the issues needing to be tackled • Tackling those issues read more..

  • Page - 255

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 As with virtually any aspect of web development, we need to carefully choose the browsers upon which we'll want our users to have an optimal experience. When we choose to support a read more..

  • Page - 256

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 11.1: An example “browser support” chart – fill one in with your own decisions! Any piece of reusable JavaScript code, to include mass-consumption JavaScript libraries as well as our read more..

  • Page - 257

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 11.2 The five major points of concern for development of reusable JavaScript The points are: 1. Browser bugs 2. Browser bug fixes 3. Missing features in the browsers 4. External read more..

  • Page - 258

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 applications destined for general Internet access, versus an in-house application used by workers chained to IE6 by a Luddite IT department! Analysis of our intended audience, our development resources, read more..

  • Page - 259

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 When writing a piece of reusable JavaScript code, we want to make sure that it's able to last for a good long time. As with writing any aspect of a web site (CSS, HTML, etc.), it's read more..

  • Page - 260

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 unspecified APIs, you should always test for your expected output, running additional cases of feature simulation (see section 11.3.3). And always be aware that future changes that could occur in these read more..

  • Page - 261

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 ENCAPSULATING OUR CODE To keep our code from affecting other pieces of code on the pages upon which it is loaded, it's best to practice encapsulation. One dictionary definition of encapsulation read more..

  • Page - 262

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 write yourself”. While this may seem a rather cynical view, when our code co-exists with code over which we have no control, we should assume the worst, just to be safe. Other code even read more..

  • Page - 263

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 11.3 Results of tests show how we can use hasOwnProperty() can detect inherited properties The test results clearly show that the ronin property, added to the Object prototype, is not considered read more..

  • Page - 264

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 element. And when that id conflicts with properties that are already part of the element, bad things can happen. Consider the following HTML snippet to observe what nastiness can ensue as a read more..

  • Page - 265

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 ORDER OF STYLESHEETS Often we expect CSS rules to already be available by the time our code executes. One of the best ways to ensure that CSS rules provided by stylesheets are defined when read more..

  • Page - 266

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 sites, breaking down browsers into graded levels of support. After a certain amount of time they "blacklist" a browser (usually when it hits an infinitesimal market-share such as 0.05%) and read more..

  • Page - 267

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 element.attachEvent("on" + type, handle); #2 } } #1 Binds using standard API #2 Binds using proprietary API In this example, we future-proofed our read more..

  • Page - 268

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Diligence is important in this respect. Since we can never fully predict the bugs that will be introduced by a browser, it’s best to make sure that we stay on top of our code and read more..

  • Page - 269

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Another example of this type of fix (also from jQuery) appears in the attribute manipulation code. Consider: if (name == "type" && elem.nodeName.toLowerCase() == "input" && read more..

  • Page - 270

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 } In this example we checked to see if a property named addEventListener exists, and if so, we assume that it's a function that we can execute, and that it'll bind an event listener to that read more..

  • Page - 271

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Because object detection has very little overhead associated with it (it's just a simple property/object lookup) and is relatively simple in its implementation, it makes for a good candidate to provide read more..

  • Page - 272

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 11.3 Putting feature simulation into practice to work around a browser bug <!DOCTYPE html> <html> <head> <title>Listing 11.3</title> <script read more..

  • Page - 273

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #4 Fixes things up if we know that the browser is buggy. #5 Sets up for testing. #6 Tests the feature with the work-around. In this code we set up some <div> elements containing read more..

  • Page - 274

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 doesn't need to perform the element checks on every stage of the loop, we can completely skip it and not pay any performance penalties in the browsers that work correctly. That is the most read more..

  • Page - 275

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 there's no way of determining if these events will fire without first binding the events and waiting for some user interaction against them, it’s hard to use them in reusable code. CSS read more..

  • Page - 276

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 AJAX ISSUES Determining if Ajax requests work correctly is another thorn in our sides. As was mentioned when we looked at regressions, Internet Explorer broke requesting local files via the read more..

  • Page - 277

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 element.addEventListener(type, handle, false); } else if (element.attachEvent) { element.attachEvent("on" + type, handle); } } Before peeking below, see if you can spot three assumptions read more..

  • Page - 278

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 12 Cutting through attributes, properties and CSS In this chapter:  Understanding DOM attributes and DOM properties  Dealing with cross-browser attributes and styles  Handling element dimension read more..

  • Page - 279

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 <script type="text/javascript"> var image = document.getElementsByTagName('img')[0]; var newSrc = '../images/ninja-with-pole.png'; image.src = newSrc; assert(image.src === newSrc, read more..

  • Page - 280

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 For example, to obtain the id of an element whose reference is stored in variable e , we could use either of the following: e.getAttribute('id') e.id Either way will give us the value read more..

  • Page - 281

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 attribute via getAttribute() returns the same value. It should be no surprise to find that this test works just fine when we load the page. Similarly, in the next test (#3), we set the read more..

  • Page - 282

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 the scenes on our behalves. But without library assist, we need to be aware of the differences and write our own code accordingly. 12.1.2 Naming restrictions Attributes, being referenced by read more..

  • Page - 283

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 hrefLang , dateTime , pubDate , isMap , srcDoc , mediaGroup , autoComplete , noValidate , radioGroup , and there are likely to be more. 12.1.3 XML differences from HTML The whole notion of properties that read more..

  • Page - 284

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 12.1.5 Performance considerations In general, property access is faster than the corresponding DOM attribute methods, especially in Internet Explorer. Let’s prove that to ourselves. Remember back in chapter read more..

  • Page - 285

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 </script> #1 Sets up variables in advance #2 Conducts test of DOM method read #3 Conducts test of property read #4 Conducts test of DOM method write #5 Conducts test of read more..

  • Page - 286

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 12.1 Results of running our performance test in the Chrome browser While these differences in speed may not be crippling for individual operations, they can add up if performed many times; read more..

  • Page - 287

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 window.attr = function(element,name,value) { #3 var property = translations[name] || name, propertyExists = typeof element[property] !== "undefined"; read more..

  • Page - 288

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Another important principle is exhibited by our attr() function itself – the function can act as both a setter and a getter simply by inspecting its own argument list. If a value read more..

  • Page - 289

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 "the action attribute is untouched"); }; </script> #1 Creates the test subject #2 Tests if properties have been stomped upon #3 Tests if read more..

  • Page - 290

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 tinkering. To get the value from a DOM attribute node, say the one for the action attribute, we’d use: var actionValue = element.getAttibuteNode("action").nodeValue; As an exercise, see if you read more..

  • Page - 291

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #2 Tests that the original node value matches what we specified in the element markup. This test passes. #3 Tests that the href property contains what we’d normally expect: the same read more..

  • Page - 292

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 While directly getting the original value of style attribute may be a comparatively uncommon operation (as opposed to accessing the resulting style object), there’s another browser problem read more..

  • Page - 293

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 element. But while this solution seems easy enough it has problems. Firstly, it’s impossible to know if the element has had any event handlers established upon it using the DOM Level 2 methods read more..

  • Page - 294

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 getting are “div” or “DIV” or even “dIv”, we ’d want to take care to normalize the names as shown in this code: var all = document.getElementsByTagName("*")[0]; for (var i = read more..

  • Page - 295

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 12.7: Examining the style property <style> #1 div { font-size: 1.8em; border: 0 solid gold; read more..

  • Page - 296

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 is normalized to RGB notation when set into the style property in most browsers (so we check both formats). WARNING The normalization is not always consistent across browsers or even within a read more..

  • Page - 297

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 It should be noted that any values in an element's style property will take precedence over anything inherited by a stylesheet (even if the stylesheet rule uses the !important annotation). One read more..

  • Page - 298

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 assert(true,style(div,'color')); assert(true,style(div,'font-size')); assert(true,style(div,'background-color')); }; </script> #1 Define style function #2 Converts name to camel case #3 read more..

  • Page - 299

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 12.3.3 The float style property One major naming headache that exists in the area of style attributes is the manner in which the float attribute is handled. By necessity, this property needs read more..

  • Page - 300

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 One other point to keep in mind, when attempting to read a pixel value out of a style attribute, the parseFloat method should be used to make sure that you get the intended value under read more..

  • Page - 301

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 All that actually sounds more complicated that the actual implementation of it. Let’s take a look at that in listing 12.9. Listing 12.9: Grabbing the dimensions of hidden elements <div> read more..

  • Page - 302

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 var withPole = document.getElementById('withPole'), withShuriken = document.getElementById('withShuriken'); assert(withPole.offsetWidth == 41, #8 read more..

  • Page - 303

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 12.5 We’ll use two images: one visible, one hidden, for testing fetching the dimensions of hidden elements If the second image were not hidden, it would appear as a second ninja just read more..

  • Page - 304

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 In a load handler, we perform the tests in a callback to a 3-second timer. Why, you ask? The load handler is so that we don’t perform the test until we know that the DOM has read more..

  • Page - 305

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 If we watch the display of the page while the test is running – remember we delay running the test until 3 seconds after the DOM is loaded – we can see that the display read more..

  • Page - 306

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 So, we can use feature simulation (remember that from chapter 11?) to determine if a browser supports opacity natively or not. Consider the code of listing 12.10: Listing 12.10: Determining if read more..

  • Page - 307

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 12.7: Visual clues as well as our explicit test shows that opacity is supported on Chrome but not versions of IE prior to IE9 Using this ninja knowledge, see if you can read more..

  • Page - 308

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Let’s now turn our eyes to yet another set of problematic style properties that cause us some pain is due to the fact that their values can take on many equivalent forms. 12.3.7 Riding read more..

  • Page - 309

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 They don’t. So we have a problem. Let’s write a test to see what the browsers do to torment us. Examine the code of listing 12.11. Listing 12.11: Determine how a browser formats read more..

  • Page - 310

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 12.8 The different browser platforms deal with different color formats quite differently! 307 Licensed to Matt a Ruby <mattaruby@hotmail.com> read more..

  • Page - 311

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Because there are all these permutations of color information formats and differences across browsers, we’re not going to take the amount of space required to develop a getColor(element,property) read more..

  • Page - 312

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 method named getPropertyValue() for retrieving the computed style of a specific style property. Unlike the properties of an element’s style object, the getPropertyValue() method accepts CSS property read more..

  • Page - 313

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 return element.currentStyle[property]; } } window.onload = function(){ var div = document.getElementsByTagName("div")[0]; assert(true, read more..

  • Page - 314

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 way, as we don’t know how expensive making this call may be, and it’s likely best to avoid repeating it needlessly. If that succeeds (and we can’t think of any reason why it read more..

  • Page - 315

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Also note that the color property, specified in both the stylesheet and directly on the element, returns the explicit value. Styles specified by an element’s style attribute always take precedence over read more..

  • Page - 316

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Part 4 Master training If you have survived the training up to this point, you can don your Ninja garb and hold your head up high among the users of the JavaScript language. For read more..

  • Page - 317

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 13 Surviving events In this chapter:  Why events are such an issue  Techniques for binding and unbinding events  Event bubbling and delegation  Using custom events  read more..

  • Page - 318

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 But DOM Level 0 events have severe limitations that make them unsuitable for reusable code, or for pages with any level of complexity. The DOM Level 2 Event Model provides a more robust read more..

  • Page - 319

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Let’s start by seeing how we can address the problems of multiple APIs and the fact that the context is not set by the IE Model by inspecting the code of listing 13.1. Listing read more..

  • Page - 320

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 parameter to the DOM event API methods. This identifies the handlers as bubble handlers; being intended for cross-browser environments, our functions do not support capture phase. If the DOM Model read more..

  • Page - 321

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Within the load handler, we fetch references to all <div> elements on the page to serve as our test subjects (#2), and iterate over the resulting collection of elements. For each read more..

  • Page - 322

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 13.1 This manual tests proves that a uniform API can bind and unbind events And figure 13.2 shows the same page, after the same actions, loaded into IE8, which does not support the read more..

  • Page - 323

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Another weakness is that this solution doesn’t even address the problem of access to the event information. So we’ve made improvements, but we’re not where we want to be yet. Can we do read more..

  • Page - 324

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 event.fromElement; // Stop the default browser action event.preventDefault = function () { event.returnValue = false; event.isDefaultPrevented = read more..

  • Page - 325

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #3 Clones existing properties #4 Returns fixed-up instance While this is a fairly long listing, most of what it’s doing is fairly straightforward and we aren’t going to exhaustively go read more..

  • Page - 326

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 (clientX/Y provides the position of the mouse relative to the window, scrollTop/Left gives the scrolled position of the document, and clientTop/Left gives the offset of the document itself. Combining read more..

  • Page - 327

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 We’ll need to have access to the full list of the handlers bound to an element in order to achieve all of these benefits, so it really makes the most sense to avoid directly read more..

  • Page - 328

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 })(); var elems = document.getElementsByTagName('div'); #4 for (var n = 0; n < elems.length; n++) { #5 getData(elems[n]).ninja = elems[n].title; read more..

  • Page - 329

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 the element using the property name in expando , and we create a new empty object associated with the guid in the cache . Regardless of whether the cache data for the element is newly read more..

  • Page - 330

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 13.3 A few simple tests show that we can store data associated with an element that’s not stored on the element itself These functions can be quite useful beyond the scope of read more..

  • Page - 331

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 13.5: A function to bind event handlers with tracking (function(){ var nextGuid = 1; this.addEvent = function (elem, type, fn) { var data = getData(elem); read more..

  • Page - 332

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Wow. That seems like there’s a lot going on, but each part is straightforward taken piece by piece. First of all, because we’re going to need some local storage (not to be confused with read more..

  • Page - 333

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 perform a check to make sure we only do this once per function (as a function can be bound as a handler multiple times if the page author wishes). At this point, we know read more..

  • Page - 334

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 PICKING UP AFTER OURSELVES We have a method to bind events, so we need one to unbind them. We didn’t directly bind the handlers, choosing to exert control over the process with the read more..

  • Page - 335

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 much as possible, releasing any unneeded storage. This is a safe thing to do because, as we saw in the addEvent() function, if the storage is needed again later, that function will simply read more..

  • Page - 336

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 The latter assumes that we have maintained a reference to the original handler. The unbinding function to accomplish all this is depicted in listing 13.7. Listing 13.7 A function to unbind read more..

  • Page - 337

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 As we’re allowing a variable length argument list, it’d probably be a good idea to check to make sure that an element was provided, as it’s not optional. How would you go read more..

  • Page - 338

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 If it is a handler that we’ve instrumented, we look through the list of handlers for it, removing any instances that we find (there could be more than one). And, as usual, we tidy up read more..

  • Page - 339

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 <div> elements) are defined after our script block. So we need to delay the execution of the rest of the script until after the DOM has been loaded. When that event fires, our read more..

  • Page - 340

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 This is far from a rigorous test. As an exercise, try your hand at writing a series of asserts that will automate testing of the functions, exercising all of the functions’ features. read more..

  • Page - 341

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 if (typeof event === "string") { #2 event = { type:event, target:elem }; } event = fixEvent(event); read more..

  • Page - 342

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 disabled (#6). Also note how we disable our event dispatcher (#8) while executing the default action as we’ve already triggered the handlers ourselves and don’t want to risk double execution. read more..

  • Page - 343

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 interesting thing has happened; anyone interested can deal with it”, and it could give a darn if anyone’s interested or not. And rather than invent our own signaling system, we can use read more..

  • Page - 344

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 13.10: Using custom events <!DOCTYPE html> <html> <head> <title>Listing 13.10</title> <meta charset="utf-8"> <script type="text/javascript" read more..

  • Page - 345

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #3 Establishes a handler for a custom event named ajax-complete on the body element that will cause the image to be hidden. No coupling here either. #4 Creates a button for us to read more..

  • Page - 346

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Figure 13.5 Custom events can be used to cause code to trigger in a de-coupled manner Notice the high degree of de-coupling throughout this example. The shared Ajax operation code has no read more..

  • Page - 347

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 small handlers that don’t know about each other. And, the page code has no idea how the shared code is doing its thing, it just reacts to events that may or may not be triggered. read more..

  • Page - 348

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 addEvent(table, 'click', function(event){ if (event.target.tagName.toLowerCase() == 'td') event.target.style.backgroundColor = 'yellow'; }); Here, we establish one handler that easily handles the work of read more..

  • Page - 349

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #1 Creates a new <div> element that we’ll perform tests upon. We’ll delete it later. #2 Tests to see if the event is supported by checking if a property supporting the event read more..

  • Page - 350

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Function that checks if the passed element is in a form. var parent = elem.parentNode; while (parent) { if (parent.nodeName.toLowerCase() === "form") { read more..

  • Page - 351

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Shirt-circuit if browser is adquate var data = getData(elem); if (elem.nodeName.toLowerCase() !== "form" && //#9 Remove piggybacking if all submit handlers read more..

  • Page - 352

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 The removeSubmit() unbinding function (#7) works in a similar fashion. We unbind the submit event as normal and exit if the browser adequately supports submit bubbling (#8). If it doesn’t, we read more..

  • Page - 353

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 }; this.removeChange = function (elem, fn) { #D removeEvent(elem, "change", fn); read more..

  • Page - 354

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 function triggerChangeIfValueChanged(e) { #K var elem = e.target, data, val; var formElems = /textarea|input|select/i; if read more..

  • Page - 355

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 All told there's a lot of code for something that should've been tackled natively by the browser. It'll be greatly appreciated when the day comes that legacy version IE have fallen by read more..

  • Page - 356

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 positioned within or outside an element that are easier to use than mouseover and mouseout . Usually we would interact with the standard mouseover and mouseout events provided by the browser but read more..

  • Page - 357

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 This situation is where the mouseenter and mouseleave events come in quite handy. They will only fire on the main element upon which we have bound them and only tell us we’ve left if read more..

  • Page - 358

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 } } })(); </script #A Tests if the browser natively supports the mouseenter (and hence, mouseleave) events. #B Adds handlers that simply invoke the handler for browsers read more..

  • Page - 359

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 technique - while it'll always fire after the DOM is ready it'll sometimes fire quite a while afterwards (but always before the final window load event). Even so, it serves as a read more..

  • Page - 360

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 ready(); } }; document.attachEvent( #G read more..

  • Page - 361

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 circumvent. But it’s not all IE’s fault, even the W3C browsers lack extensibility in the native API meaning that we still have to circumvent, and improve upon, most of the event system read more..

  • Page - 362

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431  And finally, we developed a document-ready handler that fires across all browsers to let us know when the DOM is ready to be manipulated in advance of the browser load event. All read more..

  • Page - 363

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 14 Manipulating the DOM In this chapter:  Injecting HTML into a page  Cloning elements  Removing elements  Manipulating element text If we were to open up a JavaScript read more..

  • Page - 364

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 than what would likely happen otherwise. Both of these techniques are not commonly used in everyday development, and yet they both allow you to insert elements into a page in ways that are even read more..

  • Page - 365

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 it’s a recent addition to most, and it’s likely that the legacy browsers in your support matrix include browsers without support for this method. Even IE’s implementation in its older versions read more..

  • Page - 366

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 We can do a quick pre-parse on the HTML string to convert elements like "<table/>" to "<table></table>" (which will be handled uniformly in all browsers) as shown in read more..

  • Page - 367

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 The set of problematic elements that need to be wrapped in specific container elements is fortunately a rather manageable seven, as follows (where … indicates where the elements need to read more..

  • Page - 368

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 "<th":[3,"<table><tbody><tr>","</tr></tbody></table>"], "<tr":[2,"<table><thead>","</thead></table>"], read more..

  • Page - 369

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 can be remedied by checking to see if the first generated node is a text and contains leading whitespace, if not create a new text node and fill it with the whitespace explicitly. read more..

  • Page - 370

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 window.onload = function () { function insert(elems, args, callback) { if (elems.length) { var doc = elems[0].ownerDocument || elems[0], fragment = read more..

  • Page - 371

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Altogether we now have a way to both generate and insert arbitrary DOM elements in an intuitive manner. But what about any scripting elements that are embedded in the source string? 14.1.3 read more..

  • Page - 372

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 This will cause the browser to execute the inner contents of the script element within the global scope. Listing 14.6 shows a part of the global evaluation code that's in jQuery. Listing read more..

  • Page - 373

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 document. We do this so that scripts won't be accidentally doubly executed (appending a script to a document, which ends up recursively calling itself, for example). To our ninja toolkit read more..

  • Page - 374

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 This solution has another caveat: innerHTML doesn't exist on XML DOM elements, so we're forced to go with the traditional cloneNode call (thankfully, though, event listeners on XML DOM elements are read more..

  • Page - 375

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 time so the cleanup shouldn't be any harder than just removing that one function. This is exactly how we set up our event management framework in chapter 13. This step is very important read more..

  • Page - 376

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 it will wipe out the element from Internet Explorer's memory more completely than simply doing removeChild . This step is done in addition to the normal removeChild call as shown in listing read more..

  • Page - 377

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Listing 14.12: Using textContent and innerText <div id="test"><b>Hello</b>, I'm a ninja!</div> <script type="text/javascript"> window.onload = function () { var b = read more..

  • Page - 378

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 To insert the new text contents we'll need to use a method that'll properly escape the string that we're about to insert. An important difference between inserting HTML and inserting text is read more..

  • Page - 379

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 // A text node has a nodeType === 3 if (cur.nodeType === 3) text += cur.nodeValue; // If it's an element we need to recurse further read more..

  • Page - 380

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 much simpler. But it’s nice to have a fallback for when those properties don’t cut the mustard. 14.5 Summary We've taken a comprehensive look at the best ways to tackle the difficult read more..

  • Page - 381

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 15 CSS selector engines In this chapter:  The current status of browser selector support  Strategies for selector engine construction  Using the W3C API  Some info on XPath read more..

  • Page - 382

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 already-constructed DOM caches, don't provide good error reporting, and are unable to handle any form of extensibility. The CSS selector engines that are in popular JavaScript libraries have taken read more..

  • Page - 383

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 This chapter will explore each of these strategies in depth allowing us to make some educated decisions about implementing, or at least understanding, a JavaScript CSS selector engine. We’ll start read more..

  • Page - 384

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 matching rules of element-rooted queries (calling either of querySelector() or querySelectorAll() relative to an element), as seen in Listing 15.2. Listing 15.2: Element-rooted queries <div read more..

  • Page - 385

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 document.getElementById("test"), "div b"); assert(b.length === 0, "The selector is now rooted properly."); }; </script> #A Immediate function to bind the count variable read more..

  • Page - 386

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 determined programmatically, there are a few gives: finding elements by id and simple tag- based selectors ("div") will always be faster with pure-DOM code (i.e. getElementById() and read more..

  • Page - 387

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 Using XPath expressions would work as if we were constructing a pure-DOM selector engine (parsing the selector using regular expressions) but with an important deviation: the resulting CSS selector read more..

  • Page - 388

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 <div class="ninja"> <span>Please </span><a href="/ninja"><span>Click me!</span></a> </div> </body> If we wished to select the <span> element containing read more..

  • Page - 389

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431  The results should be unique (no duplicate elements returned). Because of these gotchas, developing a top-down engine can be rather tricky. Let’s take a look at a simplified top-down read more..

  • Page - 390

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #A If no root provided, we’ll start at the very top of the document. #B Splits the selector on spaces, grabs the first term, collects the remainder, finds the element matching the first read more..

  • Page - 391

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 assert(parts[2] === "span:not(:first-child)", "span selector"); assert(parts[3] === "a[href]", "a selector"); </script> #A Reset the position of the chunker regexp (start from read more..

  • Page - 392

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 getElementsByName() is a well-implemented method that serves a single purpose: finding all elements that have a specific name (such <input> elements that have a name ). Thus it's really useful read more..

  • Page - 393

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 results. Most top-down selector implementations possess some means of enforcing this uniqueness. Unfortunately there is no simple way to determine the uniqueness of a DOM element, so we need to read more..

  • Page - 394

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 #E Run through the original array, copying elements that we haven’t “seen” yet, and marking them as we do so that we’ll know whether we’ve “seen” them or not. #F Return the resulting read more..

  • Page - 395

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 rest = parts.slice(0,-1).join(""), elems = root.getElementsByTagName(query), results = []; for (var i = 0; i < elems.length; i++) { read more..

  • Page - 396

    ©Manning Publications Co. Please post comments or corrections to the Author Online forum: http://www.manning-sandbox.com/forum.jspa?forumID=431 While there are many nuances to actually implementing a full selector engine (and, certainly, no shortage of tools to help) the situation is rapidly improving as the browsers imporve. What we read more..

Write Your Review