A Side Trip into Event Driven Programming
Notes
- We need one last element for the demo we want to understand.
- Event Driven is a mode of program operation where the program responds to "events" rather than a pre-programmed sequence of operations.
- Interactive Javascript programs are event driven.
- We have actually seen this with button presses with
.addEventListener() - But we can do much more than that.
- We have actually seen this with button presses with
- Event driven programming is used in many different applications
- GUI
- Simulations
- Most client/server systems
- Events are the main component of this paradigm
- An event is something that happens, defined by the system.
- We are probably interested in the DOM Events.
- We have explored a mouse event, click
- But there are many more.
- We will be interested in keyboard events
- keypress, keydown or keyup.
- Apparently keypress is deprecated, so we will use keydown
- We generally associate an event handler with an event
- The event handler performs an action we wish to occur when the event happens.
- When the user presses 'w', we want the character to move forward
- When the user presses the right mouse button, we want to character to turn that direction.
- In general, event handlers should be "quick" computations
- The event handler performs an action we wish to occur when the event happens.
- When an event occurs, the event handler is called
- It is usually passed an event structure which contains information about the event.
- This is usually an element drawn from an event hierarchy
- Keydown produces an keydown event.
- This element has a number of properties we can use to more precisely determine what happened.
- Just so I can remember
- Repeat is if it is being held down
- Location, try 1 on the top row vs 1 on the number pad
- Take a look at events.html
- Generally the program follows this pattern
-
declare event handlers main set up gui register event handlers while(true) if not eventQueue.isEmpty event = eventQueue.dequeue call Handlers[event] call Handlers[idleEvent] - Frequently the last loop is not handled by the program, but can be in some cases.
- Note we do not necessarily worry about how the events are placed in the queue
- This is frequently handled by an outside element such as an operating system.
-
- Frequently in such a system, their are a hierarchy (or tree) of elements that might handle the event.
- In our case
- the document
- The canvas
- The div
- the document
- There might be other elements as well.
- The main loop then is concerned about who has "focus" or where the event occurred.
- By default the canvas does not receive events.
- So we need to add
CANVAS.tabIndex = 0- Or some other positive value.
- We can add a focusin, focus, focusout event handler
- In any case if an event is not handled by the primary object, it may move up the tree
- Eventually the root will "handle" the event, but this might just be to ignore it.