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

Troubleshooting drag-and-drop functionality in a JavaScript HTML5 application resembling a Gmail upload interface

Here is a snapshot of my user interface: Each node in the tree structure is represented by an <li> element along with an <a> link. Furthermore, each folder serves as a dropzone for file uploads similar to the drag-and-drop feature found in Gm ...

Pattern to prevent consecutive hyphens and identical digits next to one another in a series

Here is a regular expression that can validate all numbers not being the same even after a hyphen: ^(\d)(?!\1+$)\d{3}-\d{1}$ For example, in the pattern: 0000-0 would not be allowed (all digits are the same) 0000-1 would be allowed 111 ...

Improve the functionality of select[multiple] to allow for single-click modifications without the need for CMD/CTRL

I am attempting to modify the default functionality of a select element so that clicking once on its options changes their selected state. Essentially, I want to eliminate the confusing requirement of holding down shift/ctrl to select multiple options. I ...

Creating an Angular JS controller that utilizes a filter for a JSON array of objects

I have the following JSON data and I'm trying to determine the number of objects with Status: 1 in the JSON. The approach I've taken so far is not working. I understand that ng-filter should only be applied to Arrays, but I'm struggling to ...

Using ajax for sending data is a breeze, but I am encountering trouble when attempting to receive data back from

I have a function that retrieves a value from an input and sends data through ajax to another PHP file. However, I am facing an issue where I cannot retrieve the result back from the PHP file even though I echo it in the ajax success function. <script&g ...

Can a client component in NextJs retrieve data from a server component?

Apologies for the way the question is phrased. I have a server component named auth.ts that retrieves user details after they log in. This server side component is located at //auth.ts export const validateRequest = cache( async (): Promise< { use ...

When receiveMessage is triggered, the FCM push notification fails to refresh the view

After following this helpful tutorial on Push Notifications with Angular 6 + Firebase Cloud Messaging, everything is working perfectly. I am able to receive notifications when using another browser. To ensure that my notification list and the length of no ...

Is it possible to modify the CSS of a single class when hovering over a child class of a different and unrelated class?

I am struggling with CSS combinators, especially when dealing with nested div, ul, and li elements. My issue involves changing the CSS of a div with the class "H" when hovering over li elements with the class "G". Since all of this is contained within a s ...

Troubleshooting tip for React JS: encountered an unexpected object error when trying to import components

I've been working on building a react app with Create React App, and everything was going smoothly until I encountered a frustrating error message: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

Other Components take turns submitting the form in one Component

Two components, CreateCandidate and Technologies are being used. CreateCandidate requires technologies from the Technologies Component. When passing the technologies to CreateCandidate, the form within CreateCandidate is submitted. Below is the code: Crea ...

Combining multiple directories into a single output using the rollup command

Alright, let's talk about my directory setup: mods/ -core/ --index.js --scripts/ ---lots of stuff imported by core/index Currently, the typical rollup process works smoothly if you want to create something like mods/core/index.min.js. However, I ha ...

Gathering feedback from a webpage using JavaScript and jQuery

I have been experimenting with different tools such as Selenium and BeautifulSoup in an attempt to scrape the contents of the following website/pages: . Specifically, I am looking to extract the reviews/sections which are dynamically loaded by JS, jQuery ...

Slideshow of table rows in HTML

On a webpage, I am populating an HTML table with a random number of rows ranging from 1 to 100. Regardless of the total number of rows, the requirement is to display only 10 rows at a time on the screen and then shift to the next set of 10 rows every 5 sec ...

Issue encountered when attempting to convert JSON string into a collection

My JSON string looks like this: "{\"Key\":3296,\"Value1\":\"Test1\",\"Value2\":\"City\",\"Value3\":\"TX\",\"Value4\":null,\"Value5\":null,\"Value6\":null}{ ...

Unable to place within div

Utilizing HTML5 to implement the "DnD" function. There is a button that adds divs. I want to be able to drag items into these newly added divs. Currently, I can only drag into existing divs and not the ones added later. How can I resolve this issue ...

Database connection error: Authentication protocol requested by server not supported

I have been struggling with the issue outlined in this link: MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client Even though I have tried following the recommendations, I am still encountering e ...

Ways to change the visibility of a view depending on a state in vuex?

If I have a button <Button> Log me in! </Button>, and I want to dynamically change its style based on the state of my Vuex app (state.user is not null). How should I properly implement this functionality? I'm considering creating a field ...

Implementing Scroll-Activated Class with Vanilla JavaScript

I'm currently developing a Vue.js project and I want to implement a feature where a "back to top" button appears when the user scrolls beyond a certain point. However, I'm encountering an issue without using JQuery. Can you help me troubleshoot t ...

What is the best way to refresh an Angular model containing nested data?

This week, I started working on a proof of concept with Angular Material where I have a table displaying nested data: <table> <thead> <tr> <th colspan="2">Employee Name</th> <th>Ovr&l ...

Issues with AngularJS Directives not functioning properly when elements are added dynamically through an AJAX request

I am facing a scenario where I have a page featuring a modal window that is created using the AngularUI Bootstrap modal directive. The DOM structure for this modal is being dynamically loaded from the server, and it is triggered to open when a specific but ...