Modify a class attribute within a function

I need to modify the this.bar property within my class when a click event occurs. The issue is that the context of this inside the click function is different from the this of the class.

export class Chart {

  constructor() {
    this.bar;
  }

  showChart() {
    ...
    let group = svg.selectAll('g').data(data).enter().append('g');
    group.append('rect')
      .on('click', function(d) {
      // My goal here is to set `this.bar = d`
      });

  }
}

Answer №1

To refer to the current object inside a function, you can assign it to a variable before entering the function block:

export class Chart {

  constructor() {
    this.bar;
  }

  showChart() {
    ...
    let self = this;
    let group = svg.selectAll('g').data(data).enter().append('g');
    group.append('rect')
      .on('click', function(d) {
          self.bar=d;
      });
  }
}

Answer №2

It's important to establish the context of this within the showChart() function:

export class Chart {

  constructor() {
    this.bar;
  }

  showChart() {
    ...
    var th = this;      // This is where you set it
    let group = svg.selectAll('g').data(data).enter().append('g');
    group.append('rect')
      .on('click', function(d) {
          th.bar = d;      
      });

  }
}

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

"Exploring the power of Vue3's composition API in managing the

Trying to implement an accordion component in Vue 3, but encountering a strange comparison issue. I'm attempting to execute a function within the accordionitem - specifically the toggle operation. However, despite numerous attempts, I am unable to mo ...

Looking to transfer zip files from a React user interface to a Node.js server backend, where I can then save the folder to a specific directory on my system

Frontend I am currently working on a feature that involves uploading a zipped folder containing CSV files from the React UI input field. import React, { useState } from "react"; import axios from "axios"; function App() { const [uplo ...

Update specific fields in a MySQL database using Express.js only if they are passed as parameters

After spending several days trying to set up a REST API, I found a helpful tutorial that explained the basics of sending requests and receiving responses. The only issue is that the tutorial uses MongoDB and Mongoose, while I'm working with MySQL. Due ...

Leveraging the boolean values of attributes within JSX statements

I have been working on a React.js project where I am trying to incorporate a data-picker plugin that requires a specific style of input-attributes: <input data-enable-time=true /> However, I have encountered an issue where webpack fails to compile t ...

How to handle an unexpected keyword 'true' error when using the `useState` hook in React?

Trying to set the open prop of the MUIDrawer component to true on user click is causing an error stating "Unexpected keyword 'true'" import React, { useState } from "react"; import { withRouter } from "react-router-dom"; impo ...

Using JavaScript to dynamically set a background image without the need for manual hard-coding

My attempt was to showcase images as a background image upon mouseover event for the div section with id 'message' by manually coding JavaScript functions for each image like this: Here is the HTML code inside the body section <div id = "mes ...

I'm attempting to access a PHP file by clicking a button using AJAX and jQuery

I am just starting to learn the basics of jQuery and AJAX. I have already attempted to solve this problem by checking previous answers on Stackoverflow, but the code provided did not work for me. I have created two pages, index.php and testing.php, with a ...

Ajax is updating the information stored in the Data variable

Recently, I reached out to tech support for help with an issue related to Ajax not executing properly due to Access-Control-Allow-Origin problems. Fortunately, the technician was able to resolve the issue by adding a file named .htaccess with the code Head ...

Utilizing a search bar with the option to narrow down results by category

I want to develop a search page where users can enter a keyword and get a list of results, along with the option to filter by category if necessary. I have managed to make both the input field and radio buttons work separately, but not together. So, when s ...

Failure to fetch data through Axios Post method with a Parameter Object

I've encountered an issue with Axios while attempting to make a post request with a parameters object to a Laravel route. If I use query parameters like ?username=user, the post request works successfully. However, when I use an object, it fails: Be ...

getting rid of the angular hash symbol and prefix from the anchor tag

I am having difficulty creating a direct anchor link to a website. Whenever I attempt to link to the ID using: where #20841 is my anchor tag. Angular interferes with the URL and changes it to: This functions properly in Chrome and Firefox, but i ...

Utilizing $resource within a promise sequence to correct the deferred anti-pattern

One challenge I encountered was that when making multiple nearly simultaneous calls to a service method that retrieves a list of project types using $resource, each call generated a new request instead of utilizing the same response/promise/data. After doi ...

TypeScript multi-dimensional array type declaration

I currently have an array that looks like this: handlers: string[][] For example, it contains: [["click", "inc"], ["mousedown", "dec"]] Now, I want to restructure it to look like this: [[{ handler: "click" ...

What to do when faced with the error message "Nodemon is not recognized as a command"?

When I try to run npm start, my Node.js is not starting. The error message displayed is: 'nodemon' is not recognized as an internal or external command, operable program or batch file. I have double-checked my environment path and also tried r ...

Exporting JSON data to CSV or XLS does not result in a saved file when using Internet Explorer

Presented below is the service I offer: angular.module('LBTable').service('exportTable', function () { function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel, fileName) { //If JSONData isn't an object, parse the ...

What could be causing jQuery's Promise.reject to fail?

Currently, I'm dealing with a REST API that resembles this stub: Snippet 1 (example based on Ruby on Rails). I have some existing jQuery code using classic callbacks: Snippet 2 It's running with these logs: case 1: [INFO] /api/my/action1: rece ...

Identifying the HTML elements beneath the mouse pointer

Does anyone know the method to retrieve the HTML tag located directly under the mouse cursor on a webpage? I am currently developing a new WYSIWYG editor and would like to incorporate genuine drag and drop functionalities (rather than the common insert at ...

Why does console.log in JavaScript exhibit different behaviors as evidenced by the code?

Exploring the behavior of console.log(obj) compared to console.log("obj"+"\n"+obj) in the code snippet below reveals two distinct output outcomes. const obj = new Object() obj.first = 'John' obj.last = 'Doe' obj.alive = true ob ...

Solving the issue of overflowing in the animation on scroll library

I've recently started using a fantastic library called animation on scroll (aos) for my web development projects. This library offers stunning and visually appealing animations. However, I encountered an issue where it causes overflow problems in my H ...

The final output message from the NPM package is displayed right at the conclusion

Is there a way to add a log message at the end of the npm install process? To enable CLI tab autocompletion run: mypackage completion >> ~/.profile <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5a5a7bab2a7b0a6 ...