Quiz

  1. I'm still a bit confused about why we can't pass f() directly as an argument. Is it because we don’t want to call the function immediately, but rather invoke it only when the user clicks on something?

    Exactly right! Contrast these two:

    
        $("some selector").click(f());
        $("some selector").click(g);
        // which is equivalent to:
        let fval = f();  // invokes f and stores the result in fval
        let gval = f;    // copies the function to a new name
        $("some selector").click(fval);
        $("some selector").click(gval);
    
    

    Clearly, the first invokes f and only gives the return value (which might not exist) to the click method.

    We (usually) want the second.

  2. I want to talk more about method chaining.

    Sure. We'll see some examples throughout the course. Basically, anytime you want to do:

    
        let obj = $("some selector");
        obj.meth1();
        obj.meth2();
    
    

    You can instead do:

    
        $("some selector").meth1().meth2();
    
    
  • Is there a specific order that we should following when using chaining? For example, should .addClass always go before .css?

    What a great question! Sometimes, it doesn't matter, such as changing two CSS values.

    Sometimes, the return value is different. For example, if we have a "point" class with setter and getter methods:

    
        let pt = new Point(0,0);
        pt.setX(3).setY(4);   // perfectly fine, in either order
        let val = pt.getX().getY();  // can't chain these, because the getter returns 3 which isn't a point
    
    

    Sometimes, we're not completely sure what the return value is:

    
    $("#fred").append("<p>hi there</p>").css('color','red');;
    
    

    Does the .css method apply to #fred or to the newly appended P? There's a definite answer, but for the sake of clarity, I would *not* use chaining if it's at all unclear. I'd do:

    
    $("#fred").css('color','red').append("<p>hi there</p>")
    // or
    let p = $("<p>hi there</p>").css('color', 'red');
    $("#fred").append(p);
    
    

    (We'll learn more about creating new DOM elements very soon.)

  • I imagine that if you got really annoyed at jQuery's flaw of allowing the wrap set to be empty, many of people who use this language must feel the same. Is there any specific reason that the jQuery developers decide to not fix this?

    Another great question! I don't know the real reason. I'm willing to speculate that there's a certain pride or even arrogance among the user base. Imagine the suggestion and response:

    Hey, I make mistakes a lot, and it would help me to put in some guardrails...

    Dude, don't be a noob...

  • I hope to practice handling clicks with jQuery in class. / There seem to be a lot of options and syntax to remember, so just practice would be helpful!

    We will!

  • This reading was pretty straightforward! / so far so good!

    Excellent!