Welcome back again to our JavaScript tutorial series. Previously, in our last Web API tutorial looked at a few examples that include DOM manipulation, the fetch API and local storage. This time, we are going to discuss event-driven programming and application state management. These are basically the complete fundamentals on how to develop an inter-active web application.
Event-driven Programming Basic
A programming paradigm, event-driven programming determines the flow of program execution by external events. Such events can be user interaction, sensor output, message passing etc.
Events and Event Handlers
In JavaScript, an event can range from a user clicking a button to data arriving from a network request. More often than not, we respond to these events by adding event handlers:
document.getElementById('myButton').addEventListener('click', function() {
console.log('Button clicked!');
});
Custom Events
Besides using existing DOM events, JavaScript also allows you to create and trigger your own custom events:
let event = new CustomEvent('myEvent', { detail: { message: 'Hello from my event!' } });
document.addEventListener('myEvent', function(e) {
console.log(e.detail.message);
});
document.dispatchEvent(event);
State Management
As applications grow in complexity, the task of managing their internal state, be it that of the user or the UI state, etc., assumes a great deal of importance. State management means maintaining a track of every input made by the user, every action taken on his part, and every response from the application within the app.
Challenges in State Management
Shared State: The shared state may be required by more than one component.
Change Tracking : There may be grave necessity for tracking changes in the state over a certain period.
Update Rules: Determine what actions would trigger state updates and how such updated states shall be processed.
Simple State Management Example
Managing simple states is possible using global variables in JavaScript:
let appState = {
isLoggedIn: false,
user: null
};
function login(user) {
appState.isLoggedIn = true;
appState.user = user;
console.log('User logged in successfully:', appState.user);
}
function logout() {
appState.isLoggedIn = false;
appState.user = null;
console.log('User logged out');
}
Event-driven programming and state management are two basic concepts related to modern web application development. That is how to develop applications in response to the behaviors of users and in consistent maintenance in its application state. Getting a firm grip on these concepts is going to make you master the art of developing advanced applications. Now, we move on to more advanced concepts and tools that enhance more your development skills in our subsequent lessons. See you in our next lesson!