0

I'm writing a class named Graph using JavaScript. Code is like following:

export default class Graph {
    constructor(props) {
        document.querySelector('#slider').addEventListener('change', function (){
            // Uncaught ReferenceError: fun is not defined
            this.fun()
        })
    }
    fun () {
    // some code
    }
}

Of course, code like this can't work.Since in the callback function, 'this' only points to the slider.Browser also complained about reference error after I deleted 'this'. Is there some method to fix this problem?

shyHelios
  • 52
  • 4
  • 2
    You can use an arrow function which will capture the right value of `this`, but careful with memory leak, if your object Graph has a limited lifetime you have to think about clearing the event listener. – Peterrabbit Oct 23 '22 at 13:49
  • I know that arrow function can solve this. But what if I want to use some of the slider's properties in the callback function? – shyHelios Oct 23 '22 at 13:52
  • 3
    then pass the `event` and use `event.currentTarget` which refers to the element the event is attached to, or `event.target` which will be the element that triggered the listener. – pilchard Oct 23 '22 at 13:52
  • 3
    You can use the event argument that is automatically passed, `event.target` – Peterrabbit Oct 23 '22 at 13:53
  • Can someone show me a code snippet about how to use event arg? I can't quite understand this. – shyHelios Oct 23 '22 at 13:56
  • 1
    Also in the case of querying by id `getElementById` is more efficient than `querySelector`. So: `document.getElementById('slider').addEventListener('change', (e) => { const slider = e.currentTarget; this.fun() });` – pilchard Oct 23 '22 at 13:57

1 Answers1

0

You can use an arrow function which will capture the right value of this, but careful with memory leak, if your object Graph has a limited lifetime you have to think about clearing the event listener. You can use the event argument to target your slider.

export default class Graph {
    constructor(props) {
        this.onchange = event => {
            this fun(); 
            console.log(event.currentTarget);
        }; // reference the callback in order to be able to clear it later.

        document.getElementById("slider")
            .addEventListener("change", this.onchange);
    } 

    clear() {
        document.getElementById("slider")
            .removeEventListener("change", this.onchange);
    }

    fun() { // some code } 
} 
Peterrabbit
  • 2,166
  • 1
  • 3
  • 19