DEV Community

Cover image for πŸš€ How to Use JavaScript Custom Events πŸ”₯ (and Why You Need Them)
Tadeu Barbosa
Tadeu Barbosa

Posted on

πŸš€ How to Use JavaScript Custom Events πŸ”₯ (and Why You Need Them)

Here's the adapted version of your post for dev.to:

πŸš€ How to Use JavaScript Custom Events πŸ”₯ (and Why You Need Them)

Custom events in JavaScript offer a fantastic way to:

βœ… Achieve modularity and reusability
βœ… Improve code organization
βœ… Facilitate communication between components
βœ… Simplify data transfer

Scenario
Imagine you’re working on a vanilla JS store website with separate components like a product list, shopping cart, and notification system. Using custom events can help these components communicate efficiently when a product is added to the cart.

Example
Here’s how you can set up and use a custom event in your JavaScript application:

// Event listener for handling product added to cart
document.addEventListener('product-added-to-cart', function(event) {
  console.log('New product added to cart:', event.detail.product);
  console.log(`Notification: ${event.detail.product.name} has been added to your cart.`);
});

// Dispatching the custom event
const event = new CustomEvent('product-added-to-cart', {
  detail: { product: new Product('Green Jacket') }
});
document.dispatchEvent(event);
Enter fullscreen mode Exit fullscreen mode

Why Use Custom Events?
Custom events simplify communication between separate parts of your application. For example, when a product is added to the cart, you might want to:

  • Update the shopping cart
  • Notify the user
  • Update the product stock

Custom events allow you to handle all these tasks without tight coupling between components, making your code more modular and maintainable.

What Do You Think?
Have you used custom events in your JavaScript projects? Share your experience in the comments below! πŸ‘‡


Photograph by Mohammad Rahmani on Unsplash

Top comments (0)