Skip to main content

Events

One way of thinking of user interaction is that the user is sending events to the nodes. For example, when the user clicks on a button, the button receives a TapDown event. The button can then respond to the event by executing code. The code passed into the onTapDown() method is called an event handler because it handles the TapDown event.

This event handler prints a message to the console when the button is tapped:

myButton.onTapDown(() => {
console.log("TapDown event!");
});
Event handlers, callback functions, and () =>

To be precise, the event handler is a callback function. You may not be familiar with the arrow function syntax, which looks like () => { ... } and might seem strange. Don't worry too much about it -- just put the code you want to execute inside the curly braces. You can read more about arrow functions here.

Alternatively, instead of arrow function syntax, you could provide a function. This code is equivalent to the above:

function logTheEvent() {
  console.log("TapDown event!");
}
 
myButton.onTapDown(logTheEvent);

Arrows function are a useful shortcut when you don't want to define a separate function to execute some code.

There are several types of events that can be sent to nodes:

  • TapDown - occurs when the user begins a touch or click within the bounds of the node.
  • TapUp - occurs when the user releases a touch or click within the bounds of the node.
  • TapLeave - occurs when the user holds a touch or click on the node, but moves outside the bounds of the node.
  • TapUpAny - occurs when the user releases a touch or click within or outside the bounds of the node.
  • PointerDown - occurs when the user begins a touch or click within the bounds of the node. Same as TapDown.
  • PointerUp - occurs when the user releases a touch or click within the bounds of the node, but the touch or click did not have to begin within the bounds of the node.
  • PointerMove - occurs when the user moves the mouse or touch within the bounds of the node.
tip

The variety of tap and pointer events may seem confusing, and the difference between a tap and a pointer may also be hard to understand. In most cases, you'll just need the TapDown and TapUp events. The other events are useful for more advanced scenarios.