The DOM has built-in support for Event-Driven programming. This means your application can sit around and wait for user input or other Events. Once an Event
has occurred, its information is sent to a function called an EventListener
.
We saw an example of this during the last section for handling change
events from <input>
elements.
Event Listeners
Using classical JavaScript DOM Element Attributes
/* Code */
function handleClick() {
...
}
/* View */
<button onclick="handleClick()" />
Using JSX to inject EventListeners
.
/* Code */
class ViewModel {
handleClick() {
...
}
}
/* View */
<button onclick={viewModel.handleClick.bind(this)} />
Using TypeScript arrow methods to simplify syntax.
/* Code */
class ViewModel {
handleClick = () => {
...
}
}
/* View */
<button onclick={viewModel.handleClick} />
Asynchronous Programming
JavaScript can be written as asynchronous code, meaning it doesn't have to always run in order. Most of the time this isn't the case, as instructions are executed one after another.
Event Propagation
Event.stopPropagation();
Event.preventDefault();