Anonymous Functions!
Goals:
- Make use of anonymous functions for event handlers Further explore jQuery methods
plan
, done
, and each
.
Coding Snippets:
- The jQuery
each
method facilitates iteration over the elements of a jQuery collection. This higher-order function accepts a callback, which in this example is defined anonymously. The callback accepts two arguments, representing the index of iteration and the current element.
Math and Computer Concepts:
- An anonymous function is defined without assigning it a name. We simply put the function definition where we normally would put a reference to that function.
- One reason to use anonymous functions is convenience. They require less typing and their use often simplifies our code, such as when defining a callback that is used only once.
- An additional benefit to anonymous functions is that their use reduces chances for namespace collisions: we don't have to worry that the name chosen for the function is a variable name already used elsewhere in our program.
Activities:
Save each of the following in a folder called AnonymousFcns.
- PlanToStayInside: Previously you learned to precede calls to functions that do not get executed as part of the animation queue, such as
inside
andgetxy
, withawait
done
defer()
. A more elegant solution is to place this code in a callback which is passed to theplan
function. Write a program that instructs a sprite to move randomly about the screen, but relies onplan
(and an anonymously-defined callback) to resolve animation-queue challenges. - MoveOnWhenDone: Write a program that uses arrow keys to direct the sprite around the screen, but this time, define your event handlers using anonymous functions. Additionally, make use of
done
to prevent keystrokes from queueing up additional instructions for animations before the current animation is completed.done
works similarly toplan
, except that the code passed to it—as a callback—is executed once all animations in the queue have completed. In your script, when a key is pressed, "disable" all buttons until the animation has been fully carried out. The callback todone
should contain the code needed to make the keys functional again. - jQueryEach:Write a script that makes use of the
each
method to move turtles randomly about the screen. The callback function should not only tell the turtles to turn and move, but should also contain logic to keep them from wandering off the screen.