Skip to content

How to Create Own Custom Event from JavaScript

Last updated on March 27, 2020

In this blog post, you will learn How to Create Own Custom Event from JavaScript.

Introduction

There is a traditional way of exposing an event and which is nothing but Event type.

This feature is superb useful when you expect to fire up your own event but with the customized data.

How to Creating Custom Event

This addition of a new feature to JavaScript Eco System helps us to create our own Event.

At any point in time, you can pass your own desired data with the help of the DOM event handler.

Item Selected from Price Model Web Component

To explain this in detail, I take the code sample from the recent work of the Price Model web component.

The idea here is that when the user clicked on the chosen pricing plan the selected event gets fired up.

Let’s say we have a template mark-up as given below,

<main class="container"> 
  <div class="package"> 
    <div class="pkg-info item"> 
      <span class="package-name"></span> 
    </div> 
    <div class="price item"> 
      <div> 
        <span class="money-symbol"></span> 
        <span class="money-value"></span> 
      </div> 
      <div class="term">Per Month</div> 
    </div> 
    <div class="feature item"> 
      <ul class="feature-list"></ul> 
    </div> 
    <div class="action item"> 
      <button class="btn">Select</button> 
    </div> 
  </div> 
</main>

After defining Shadow-DOM from the constructor of Web Component,

this.$cta = this._shadowRoot.querySelector('.action .btn'); 
this.$cta.addEventListener('click', this.selectPricing.bind(this));

The event handler method for Call To Action button is selectPricing.

selectPricing() {
    try { 
      this.dispatchEvent(new CustomEvent('item-selected', { detail: { pkgName: this._data.package_name } })); 
    } catch (error) { 
      throw error; 
    }
}

Here, I created item-selected custom event that exposes selected package name.

And I append the selected package name to event detail object. Thus, When clicking on CTA button the event handler would receive detail property from event parameter.

this.$priceModel.addEventListener('item-selected', (e) => { 
    custom.log(e.detail);
});

I hope this would be really helpful for you. I am really excited to know more about how you used this feature in your project. You can post that in the comments section.

References

Published inAngularFrameworksJavaScriptReact