0

I'm writing a simple js class that looks for a div and injects into it an img tag.

I need to call an internal function stop() if the user click on the div.

class PreDS {

constructor() {
    console.log("[PreDS] constr")
    this._el = document.querySelector(".imgOrari")
    if (this._el){
        this._el.innerHTML = "<img id='imgOrariImg'>";
        this._el.onclick =
            function(){
                console.log("[PreDS] click _el")
-->             stop("click")
            }
    }
    else console.error("class imgOrari not found")
}


stop(){
...
}

The problem is that the onclick handler defined like this, is not in the context of the object, so the function is undefined.

How can i recall the function?

SteMMo
  • 392
  • 1
  • 4
  • 23
  • 2
    Use `this.stop(...)` and have a look at [How to access the correct `this` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Felix Kling Feb 05 '20 at 12:58

1 Answers1

1

Use ES6's fat arrow functions that transfer the context and don't create a new one like ES5's function(). Also you need to use this.stop() and not just stop()

this._el.onclick = () => {
                console.log("[PreDS] click _el")
                this.stop("click")
            }
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • Would `this._el.onclick = this.stop` work? – Ben Aston Feb 05 '20 at 13:02
  • 1
    @Ben: Depends on whether `stop() {}` needs `this` to refer to the class instance or not. If yes, it won't work. But in that case you can bind the function: `this._el.onclick = this.stop.bind(this)`. – Felix Kling Feb 05 '20 at 13:05
  • Solved: the fat arrow function solved the context problem. Thanks. – SteMMo Feb 05 '20 at 13:20