Easiest method for implementing event emitter in ES6

Here is the current setup for my event emitter:

class Table {

  set onDiscard(cb) {
    this._onDiscard = cb;
  }

  notifyDiscard(s) {
    if (this._onDiscard) {
      this._onDiscard(s);
    }
  }
}

Dealing with multiple events using this method can become cumbersome.

Is there a library, feature, or alternative implementation that would allow me to simplify this process into just one line of code?

Answer №1

Check out this example that allows for multiple event handlers:

class CustomEvents {
    addEventListener(eventName, callback) {
        this['_on' + eventName] = this['_on' + eventName] || [];
        this['_on' + eventName].push(callback);
    }

    triggerEvent(eventName, eventData) {
        this['_on' + eventName] && this['_on' + eventName].forEach((callback) => { callback(eventData) });
    }
}

var events = new CustomEvents();

events.addEventListener('click', function() { console.log('Clicked'); });
events.triggerEvent('click');

Answer №2

Have you considered using a string for the event type?

class Database {
  on(eventType, callback) {
    this["_on" + eventType] = callback;
  }
  
  notify(eventType, data) {
    if(this["_on" + eventType]) {
      this["_on" + eventType](data);
    }
  }
}

Answer №3

Are you referring to ES6 specifically or the broader ECMAScript standard? Since ES6 maintains backwards compatibility, it is possible to utilize any event library in ES5 (JavaScript) that is available.

I recommend exploring Backbone, particularly for tasks involving model/view logic, as it excels in this area. Backbone boasts a minimalist design, its own event emitter/listener system (refer to the Events section), which closely resembles the one used internally by the DOM, and facilitates clean separation between view and model logic.

Recently, I developed a basic application as a proof of concept using Backbone with ES6, and found it to be fully compatible as anticipated. Extending base classes through ES6's extend function mirrors underscore's extend behavior when utilizing extend as recommended in Backbone's documentation.

In my case, I utilized Babeljs for transpilation purposes.

Answer №4

In the world of Ember, there are already effective methods for emitters and notifiers that work seamlessly. It's unnecessary to look elsewhere or attempt to blend in a different class mechanism like the one found in ES6. Ember has its own system in place that functions well, so trying to mix it with ES6 classes may lead to unnecessary complications.

It's important to remember that ES6 classes are essentially just a more simplified version of JS prototype-based classes. If you're already utilizing Ember, there's little incentive to create your own emitter/notifier system using prototype-based classes. Why introduce a second class paradigm when you're already comfortable with the existing one? Stick with what works best for you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to tally a score after analyzing two spans in Javascript?

I have 3 spans where 2 contain an alphabet each. The third span is left blank for the result of comparing the first 2 spans. I need to display the result in the last span, showing a value of 1 if the two spans contain the same alphabet. Can anyone sugges ...

Searching for a deeply nested JSON property with lodash

I am dealing with a JSON API response that has the following structure: [ { title: "top1", sections: [ { section_title: "section1", content: [ { content_title: "title1", content_id: "id1" ...

Reviewing the element names in a jQuery-selected array of objects

I'm new to javascript and the jquery library and I need to work with an array of input fields that have specific names for validation. Each input field is named NS[0], NS[1], etc., and the total number of these fields is generated dynamically in the c ...

The Angular controller encountered an unexpected token

I have organized all my Angular controllers in one controller file. However, I encountered an issue when trying to print out a specific part of my object array at the end of a controller. Everything worked fine until I added a new controller after the cur ...

Disabling GPS with HTML5/phonegap: A step-by-step guide

Looking to create a function that can toggle GPS on and off for both iPhone and Android devices ...

What is the best way to create a grid item that maximizes the available space in ReactJS Material-UI?

Currently, I am working with the material-ui grid system in a reactjs project. In a column grid container layout, my goal is to display two grid items and have a third item fill up the remaining space between them. Essentially, I want it to look like this: ...

The event is being triggered on two separate occasions

Hey there! I'm trying to bind the onclick event to both a parent and child element using the same method. However, I'm running into an issue where the event is being fired twice. Any suggestions on how to prevent this from happening? <div id= ...

What advantages does the use of $(e).attr(name,value) offer compared to using e.setAttribute(name,value)?

Scenario: The variable "e" represents an element of type "HtmlElement" and not a "css selector" I am referring to any attribute, not just the standard allowed ones like "atom-type" or "data-atom-type". Regardless of the attribute name, will it function wi ...

The absence of CORS headers detected in XMLHttpRequest

I am currently trying to execute an ajax call to a remote server, only for developmental purposes. I have configured CORS on my server, which is why when I request the resource through the browser, it shows that the CORS headers are present. https://i.sta ...

Utilizing Angular 1.5 and ES6 to Enhance Dependency Injection

Hi there, I am currently exploring Angular and attempting to integrate ES6 into my workflow. I seem to be facing an issue with dependency injection where I cannot seem to get it working as expected. Here is a snippet from my index.js file: import ...

What is the best way to store items in localStorage within Angular version 4.4.6?

I have been working on implementing a basic authentication system in Angular 4.4 with MongoDB as the backend database. login.component.ts import { Component, OnInit } from '@angular/core'; import { AuthService } from 'app/services/auth.ser ...

Obtain the corresponding element from the selectors utilized in the jquery.is function

$("#see1, #seeAlso1, .see").is(':checked') This code snippet will give you a boolean result. Are you looking for a way to retrieve the first element that matches and returns 'true'? ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

Refreshing image does not reload

function updateimage(){ $("#fileimg").attr("src","path/to/image.jpg"); $('#fileimg').fadeIn('slow'); setTimeout(updateimage, 5000); } Greetings, I am trying to refresh an image every 5 seconds but it's not working as ...

Error copying cell width attribute when using border collapse

Currently, I am attempting to duplicate a table header by copying the tr HTML and then replicating the th widths. Unfortunately, this method is unsuccessful as the widths are displayed as (width minus W) pixels when border: 'Wpx' and border-colla ...

The properties of a JSON object are not explicitly defined

When I make an AJAX call, I receive a JSON object and log it using this code: console.log(response); This is the response that gets logged in the console: {"filename":"new.jpg","orientation":"vertical"} However, when I try to access the orientation pro ...

Display a dialogue box when encountering a Vuetify error. Only open the dialogue box under certain conditions

I am currently implementing vuetify into my project. The main issue I am facing is related to the dialog component, which I only want to open in case of an error. The scenario involves a button calling a backend service to save a product in the database, a ...

Conceal the parent component's <button> element within the Child component

I'm facing an issue with hiding a button in my parent component from the child component. I tried using props to bind the element and v-show directive to hide it, but instead of just hiding the button, it ends up hiding the entire tab. Take a look at ...

Something seems off with my code. It's causing a barrage of errors to appear on the browser

JavaScript is a whole new world for me, and I'm struggling with all these errors. The goal here is simple: click the "generate" button, and under "Most Recent Entry," display the current temperature for the entered zip code, today's date, and th ...

Eliminate unneeded null and empty object data attributes within Vue.js

When sending object data to an API, I have multiple states but not all of them are required every time. Therefore, I would like to remove any properties from the object that are null or empty strings. How can I achieve this? export default { methods: { ...