Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

events


callbacks

events are handled using callbacks


addEventListener()


example: load, click and `keydown

in this first version we are going to use globally defined functions

Loading...

timeline

here’s a timeline of what is going on


example - observations

notice from the example :


other types of events

setTimeout(foo, 3000)  // call foo once in 3000 ms
setInterval(foo, 3000) // call foo every 3000 ms

code-generated events (optional)

you can create your own event by code, e.g. :

const foo = () => console.log("foo ! ")
const event = new Event('myevent')
// Listen for the event - on any element
document.body.addEventListener('myevent', foo, false)

// Dispatch the event.
document.body.dispatchEvent(event)

anonymous functions

due to the extensive use of callbacks in JavaScript, having to name every function is annoying
for this reason, JavaScript has 2 convenient ways to create anonymous functions:


anonymous function usage

in this context, it is common to create functions on the fly, e.g.

document.addEventListener(
    "DOMContentLoaded",
    // the expression on the following line
    // returns a function object
    () => console.log("page loaded")  
)

the example with arrow functions

Loading...

functions vs arrow functions

const arrow_without_brackets = (a) => a*2
const arrow_with_brackets = (a) => { a*2 }

console.log("arrow without brackets:",
            arrow_without_brackets(3))
console.log("⚠️ arrow with brackets: ⚠️",
            arrow_with_brackets(3))
arrow without brackets: 6
⚠️ arrow with brackets: ⚠️ undefined
const function_with_return = function (a) { return a*2 }
const function_without_return = function (a) { a*2 }

console.log("function with return:",
            function_with_return(3))
console.log("⚠️function without return: ⚠️",
            function_without_return(3))
function with return: 6
⚠️function without return: ⚠️ undefined

limits of callbacks


practice: blinking background

now could be the right time to see the exercise on a blinking background !


practice: a dynamic grid - step 2

you can now go and finish the TP on the dynamic grid on github !



closures

see also this thorough article on closures on javascript.info


closure example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// here the 'context' variable is not visible

{  // <- this is the block where 'context' is visible

  let context = {a:1, b:2}
  setTimeout(
  // here the 'context' variable is visible and remains valid
  // even if we leave the block
    () => console.log("in the callback: ", context),
    2000)
  console.log("NOW timeout armed")

}  // <- end of context's scope

// and so from here 'context' is no longer visible
// let us prove it:

try {
  context
} catch(err) {
  console.log(`OOPS not visible in global scope: ${err.message}`)
}

// BUT: wait for 2s and see the callback still triggers properly
// it means that the 'context' variable somehow is still alive

takeaway


let vs var

a broken example

// again you need to run this in the browser console

function ko() {
  // DO NOT USE var IN YOUR CODE !
  for (var i=1; i<=3; i++) {
     setTimeout(() => console.log("ko, i =", i),
                100*i)
    }
}

ko()
function ok() {
  // use let instead
  for (let i=1; i<=3; i++) {
     setTimeout(() => console.log("ok, i =", i),
                100*i)
    }
}

ok()

takeaway