Anonymous Functions!
Goals:
- Make use of anonymous functions for callbacks
- Further explore jQuery methods
plan
,done
, andeach
.
Coding Snippets:
- The jQuery
each
method facilitates iteration over the elements of a jQuery collection. This higher-order function accepts a callback with two arguments: the index of iteration and the current element. plan
delays execution of code passed to it, via a callback, until the appropriate point in the animation queue. In this example,plan
ensures that thecss
statement is executed after the call towear
.
Math and Computer Concepts:
- An anonymous function is defined without assigning it a name. Simply put the function definition where you normally would put a reference to a function.
- Anonymous functions are particularly useful for defining callbacks that are used only once. Aside from saving coders a few keystrokes, use of anonymous functions 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.