Is there a quick way in ES6 to assign member functions as event listeners?

This question is unique and not a repetition of the query posed in How to access the correct `this` context inside a callback?

Although some answers may overlap, the Question at hand differs. The comments below the answers indicate varied solutions, particularly as this discussion pertains to ES6 rather than traditional JavaScript. Furthermore, it specifically addresses event listeners, not just callbacks, which leads to alternative approaches beyond basic callback functions.


In instances where a function within a class needs to be invoked by an event, there tends to be a significant amount of redundant code that needs to be written

class SomeClass {
  constructor(msg, elem) {
    this.msg = msg;
    elem.addEventListerer('click', (...args) => {  
      this._onClickListener(...args);              
    });                                            
  }
  _onClickListener() {
     console.log(this.msg);
  }
}

Is there a more concise syntax in ES6 for using class methods as event listeners? Ideally, I would prefer to achieve something like

class SomeClass {
  constructor(msg, elem) {
    this.msg = msg;
    elem.addEventListener('click', this._onClickListener);
  }
  _onClickListener() {
     console.log(this.msg);
  }
}

However, this approach does not function as intended. Without the additional code, the proper assignment of this does not occur.

class SomeClass {
  constructor(msg, elem) {
    this.msg = msg;
    elem.addEventListener('click', this._onClickListener);
  }
  _onClickListener() {
    console.log(this.message); 
  }
}

var s = new SomeClass("hello", document.querySelector("button"));
<button>click me</button>

Answer №1

Make sure to properly associate the context:

class AnotherClass {
  constructor(data, element) {
    this.data = data;
    this._onHoverListener = this._onHoverListener.bind(this);
    element.addEventListener('mouseover', this._onHoverListener);
  }
  _onHoverListener() {
     console.log(this.data);
  }
}

An added benefit of using this approach is that you can easily remove the listener by calling

element.removeEventListener(this._onHoverListener)

Answer №2

class MyClass {
  constructor(message, element) {
    this.message = message;
    element.addEventListener('click', this._onClick.bind(this));
  }
  _onClick() {
    console.log(this.message);
  }
}

var m = new MyClass("hello", document.querySelector("button"));
<button>click me</button>

It seems like I may not completely grasp your question, but it does function properly with bind.

Essentially, bind produces a duplicate of the bound function with this constantly set to the specified reference. (You can also bind arguments, but that's not applicable in this scenario.)

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

Be mindful of potential missing dependencies when utilizing event listeners and states within useEffect

Whenever I utilize the addEventListener() method alongside trying to access some state within the useEffect, I consistently face the same issue. Adding the state as a dependency is not an option, as that would result in multiple event listeners being creat ...

Using HTML and JavaScript to add variables into the URL within the window.location

I have been struggling to incorporate longitude and latitude into the URL. Despite researching various topics online, I have not found a solution that works for me. Below is the HTML code that showcases the issue. When you click the "Show Position" button ...

Having trouble getting a new input box to be added when clicking with AngularJS?

I am facing an issue with adding dynamic form fields to the database using PHP. I have utilized angular for this purpose, but only the last form field is getting inserted into the database. To address this, I attempted using arrays and loops to increment a ...

Extract URL as a parameter for $.getJSON using JavaScript

When attempting to include a URL as a parameter along with several other parameters in my frontend to make a JSON request to my Django backend, I am encountering the familiar 404 error - not found. Django urls.py path: path("updateAssignment/<iD&g ...

I'm having trouble getting the [resetFilterOnHide]="true" functionality to work with primeng 5.2.7. Can anyone provide a solution for this issue?

I'm experiencing an issue with the p-dropdown component where the [resetFilterOnHide]="true" attribute isn't working as expected. When I type in the filter bar, close the dropdown by clicking outside of it, and then reopen it, the entered filter ...

Is it possible to utilize the return value from an asynchronous function within useEffect as the default value for useState

Check out this simple example I've put together https://codesandbox.io/s/4zq852m7j0. In the example, I am fetching data from a remote source and attempting to use the returned value as the input for my textfield. const useFetch = () => { const ...

Executing a callback within a promise: a step-by-step guide

One of my functions is designed to take a Section and return a Promixe. router.get('/menu_section', (req, res) => { Section.read(req.body) .then(d => { send(d, res); }) .catch(e => { e ...

What is the process for packaging my JavaScript application?

Based on my research, I'm curious to know what is the most effective method for distributing a Javascript application. Is it considered best practice to distribute applications using npm packages? Or is npm primarily used for distributing frameworks? ...

There seems to be a glitch in the AJAX code

I am currently working on a project that involves displaying categories and subcategories of products on a webpage. When users click on either a category or a subcategory, AJAX is used to send the selected item to a php script which then generates HTML cod ...

Angular.js: Applying a style to elements beyond the current scope based on the selected route

I'm looking to dynamically add classes outside of the current scope. Specifically, I need to add classes to the header, main, and footer elements as shown below: <header class="{{pageClass}}"></header> <main class="{{pageClass}}" ng-vi ...

How come the information isn't being transferred between components?

Is my method correct if I want to pass the this.prompt() function from TitleBar to Portfolio? This is what my index.html file looks like: var TitleBar = React.createClass({ render: function() { return( <div className="jumbotron"> ...

What is the method to change a string into an array using javascript?

Here is a JavaScript variable containing the following string: var days = "1,2,3"; Now, I am looking to transform it into a JavaScript variable with JSON format like this: jdays = ["1", "2", "3"]; Is there a way to achieve this? ...

Harnessing the power of external Javascript functions within an Angular 2 template

Within the component, I have a template containing 4 div tags. The goal is to use a JavaScript function named changeValue() to update the content of the first div from 1 to Yes!. Since I am new to TypeScript and Angular 2, I am unsure how to establish comm ...

Getting the mouse location with three.js: A step-by-step guide

Hey there, I'm currently working with IcosahedronGeometry. I've added CircleGeometry to each of its vertices. My goal now is to allow the circle to sense the mouse movement and follow it when it gets close. To achieve this, I've created a Ri ...

The express post request body fails to appear, rendering it empty

Server Side Code const express = require('express'); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended:true })); app.post('/',(req,res)=>{ console.log(req.body) }) Client Side Code const da ...

What's the reason behind the malfunction of this code on Chrome?

After recently installing Mobiscroll, I have been using the date scroller feature with the following code to manage the textbox. <script type="text/javascript"> $(function() { // create a datepicker with default settings $("#begi ...

Decide whether an angular rotation is within the camera's field of vision inside a spherical object

Seeking assistance with a three.js project. I have set up a camera inside a SphereGeometry at position (0,0,0) and am projecting an image on the sphere's wall. My goal is to create interactive JS elements outside of the threejs framework that respond ...

JavaScript featuring Ajax functionality

Although I have limited experience in web programming, I am currently testing a simple add-on to integrate with my app. The webpage I have created displays multiple rows, each containing an editable field for user input. After the user inputs data into th ...

Utilizing an Angular Directive to set up various jQuery plugins simultaneously

As a newcomer to Angular, I must ask for patience with any lack of knowledge evident in this post. Specifics: In my project, I am utilizing CodeIgniter alongside Angular.js, and I am grappling with the process of initializing multiple plugins within my a ...

Press the button to reveal the table - jQuery/JavaScript

Can you please provide guidance on how to hide the inner HTML table when the page loads and then display the table with results only after clicking the search button? I do not want to show an empty table. Below is the code snippet that I have tried: Howev ...