What is an event handler?
In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place.
An event is an action that takes place when a user interacts with a program. For example, an event can be a mouse click or pressing a key on the keyboard. An event can be a single element or even an HTML document.
Let's say a mouse click on a button displays the message "DOM Event." The event handler will be the programmed routine whereby each time a user clicks on the button, the message "DOM Event" is displayed.
An event is a meaningful element of application information from an underlying development framework. There are many types of events, either from a graphical user interface (GUI) toolkit or some input-type routine.
On the GUI side, events include keystrokes, mouse activity, action selections or timer expirations. On the input side, events include opening or closing files and data streams, reading data and so forth.
Here are some common examples of an event handler:
- A notification pops up on a webpage when a new tab is opened.
- A form is submitted when the submit button is clicked.
- The background color changes on a mouse click.
How to program an event
Let's take the above example, where an action occurs after the user clicks on a button. Such an event is known as a click event. Typically, web events form a part of the browsers' application program interface (API).
Today, the standard way of registering an event handler is using the addEventListener() method. For this, the programmer needs to specify the event's name and the function that responds to it.
Some software architectures operate almost entirely by producing, managing and consuming events. Nearly all software architectures must include some event handling capabilities, if only to deal with out-of-bounds conditions and errors.
The difference between event handlers and event listeners
The terms event handler and event listener are often used interchangeably. However, there is a slight difference between the two. These are two ways of handling events.
When a code runs after an event takes place, this is known as registering an event handler. On the other hand, the event listener listens to the event and then triggers the code for handling the event.
See also: event-driven application, event-driven architecture (EDA), event handling, event forwarding, complex event processing, business event management, event stream processing.