ZIM - Code and Learn Coding with ZIM for JavaScript and HTML Canvas with CreateJS


Practice with ZIM CODE see the Learn Page for tutorials


Lesson 03 - Functions and Events


A function is a block of code that we can run whenever we call the function. This lets us put repeated code in one place - which is more efficient and consistent. In this sense, functions help us with abstraction - as we will explore in a future lesson. Functions can also be used to just organize our code.

Below are the ZIM CODE convenience functions, many of which are shared by coders around the world.

In JavaScript, a function is what a class is made from - such as all the ZIM Display Classes we were using the first two lessons. Also, a method is a function stored on a class and run on its object. Here are the ZIM METHODS.

An event is how we handle interactivity. We capture an event when something happens like a mouse click, a keydown, an image load, etc. We can then call a function to do something when the event happens. This is how all the interactive media EXAMPLES work!

Let's take a look at REFERENCE and PRACTICE sections first for functions and then for events!


Function ► What IZ Function
A function can be declared with the function keyword followed by the name of the function (the identifier) then round brackets ( ) then squiggly brackets { }. Inside the squiggly brackets is the block of code that executes when the function runs.

function message() { // the block of code that will run (indented) // can be many statements }

The function does not run until it is called (executed). We call the function by using its name (indentifier) and round brackets (). The terms call, run and execute are all the same thing.

function message() { // the block of code that will run (indented) // can be many statements } message(); // calling the function

A declared function is hoisted to the top of its scope. The scope is the containing function or global if the function is not inside a function. This means that you can call the function before you define it.

message(); // calling the hoisted function function message() { // the block of code that will run (indented) // can be many statements }

We have seen parameters when making objects from classes or when running methods. So the same applies to functions (as those others are functions).

// zog() is a ZIM function that logs to the console (F12) // the plus sign (+) means concatenation (join) for Strings function message(avatar, words) { zog(avatar + " says " + words); } message("Dr. Abstract", "Aloha!"); // calling the function

Functions can return a value using the return keyword. Nothing in the function runs after a return. If the function does not return a value then the return value is undefined. The returned value is placed in the code right where the function is called.

function area(width, height) { return width * height; } var cost = area(20, 10) * .5; // the return value of 200 gets multiplied by .5 // so cost is equal to 100

A function defines the scope of any variables or functions declared within it.

// variables are available within the function they are declared // they are said to be global if not declared within a function // usually we avoid setting variables in the global scope // so that our code does not interfere with other code that may be there function test() { var a = "hi"; zog(a); // logs to console the word "hi" } test(); zog(a); // error! a is not defined // in JavaScript 6, we use let instead of var // let has a scope of any { } in which it is defined // whereas var has the scope of { } belonging to functions only let a = 8; if (a > 7) { // we see conditionals later var x = 10; let y = 20; // only available inside { } } zog(x); // logs 10 in the console zog(y); // error! y is not defined


We will use many many functions as we code. Soon, making them will be second nature. Remember that we define (make) functions and then to run them, we must call (execute) the function.

1 Basic Functions Show


Function Literal
In JavaScript, functions are objects made from the Function class. We can also make function literals (anonymous functions or function expressions). These can be assigned to variables or passed as parameters or be treated like any other object.

var test = function() { zog("testing!"); } test(); // logs testing! to the console // the function is NOT hoisted when it is assigned // so it cannot be called before the assignment

new Rectangle() .center() .animate({ obj:{scale:2}, time:2000, // set the call property to a function literal // animate passes in the target of the animation call:function(target) { target.remove(); stage.update(); } });

Stage Update
Function literals are often used in asynchronous cases - that is something that runs later (out of sync). Often when we make changes at a later time, we need to update the stage so the change can be seen. We use the update() method of the stage to do so.

Other asynchronous cases are ZIM timeout() and interval() functions that match JavaScript setTimeout() and setInterval() but with more features. These run functions after a certain time - or repetatively after certain times. The ZIM Ticker() lets you run a function at the app framerate (60 fps / 30 fps mobile). Another example is calling a function when an event happens - which we explore in the second part of this lesson.

timeout(1000, function() { zog("logs after one second;"); // changes need a stage.update(); }); interval(1000, function() { zog("logs each second - like a timer"); // changes need a stage.update(); }); interval(1000, function() { zog("run five times starting right away"); // changes need a stage.update(); }, 5, true); Ticker.add(function() { zog("very fast"); // automatically updates! });

Arrow Functions
In ES6 we have Arrow Functions for function literals:

var message = (word) => { zog(word); } message("hi"); // logs hi to the console var short = word => word + ", wonderful"; short("hi"); // logs hi, wonderful to the console // if there is a single parameter you do not need the () // if there is a single statement - the value will be returned // put () around an object literal to return an object literal

Let's try out some functions and then we will have a look at events - which call functions.


Function literals (anonymous functions or function expressions) are used when assigning a function to a variable, a property or passing a function as a parameter.

2 Function Literals Show


Events ► What IZ an Event?
We use the on() method to capture events. This is very similar to the traditional JavaScript addEventListener() but shorter - and there are a couple extra features.

Put the object that is receiving the event first, then the on() method with the first parameter being the event type as a String and the second parameter being the function to call when the event happens:

// use the cur() method to add a pointer cursor // to tell the user that the object is interactive var circle = new Circle().center().cur(); // do NOT chain the on() method as it does not return the object circle.on("click", function() { circle.removeFrom(); stage.update(); });

// adding true as the third parameter runs the event only once // this is something addEventListener does not have circle.on("click", function() { circle.removeFrom(); stage.update(); }, null, true);

// use off() to remove an event // store the event return value to use with off() var myEvent = circle.on("click", function() { circle.removeFrom(); stage.update(); }); timeout(5000, function() { // remove the event after 5 seconds // use the same syntax as on // but replace the function with the stored reference circle.off("click", myEvent); });

Types of Events
Not all objects have the same events but here are common events:

Common Events

See the docs for lists of events an object has. These are near the bottom of the description after parameters, methods and properties.

Event Object
The event function is given a single parameter which is an event object. We often collect this as the identifier, e. The event object holds information about the event such as the target, the currentTarget, the keyCode (for keyboard events), etc.

The target is what causes the event. The currentTarget is the object the event is placed on. Often these are the same unless the event is placed on a Container.

var circle = new Circle().center().cur(); var rectangle = new Rectangle().addTo().cur(); circle.on("click", remove); rectangle.on("click", function(e) { e.target.removeFrom(); // removes what is clicked on stage.update(); });

var holder = new Container(stageW, stageH).addTo(); var circle = new Circle().center(holder).cur(); var rectangle = new Rectangle().addTo(holder).cur(); holder.on("click", remove); function remove(e) { e.target.removeFrom(); // removes what is clicked on in the holder // e.currentTarget.removeFrom(); // would remove the whole holder stage.update(); };

Let's try out events in a PRACTICE section!


Remember that events happen after the original stage.update(). This means that there needs to be another stage.update() inside the event function.

3 Events Show


We have seen examples of types of functions and events. There are more but these are most of the variations. Please practice them a few times. Learning syntax will help reduce problems as you code and let you concentrate on the logic. We look at logic and organization in the next lessons with conditionals, loops, arrays and abstraction.

LESSON 02 - Config Objects and Animation LESSON 04 - Abstraction