#How to put code in a closure?

4 messages · Page 1 of 1 (latest)

open ferry
#

Hello, I am a beginner with javascript and I'm trying to reference my class object in an event function (if that's even what it's called?). However, when I am in the event function (which might also be a class method but idk for sure), I can no longer reference my class object's other methods or variables via this.method() because this has been remapped to the event target. I did some research and found that maybe a closure is what I need, but I do not know how to implement one even after watching a tutorial. If anyone could help me out I'd appreciate it a lot, thanks.

So I have a checkEvents method

checkEvents() {
        const submit = document.getElementById("submit-button");
        submit.addEventListener("click", this.submitClicked);
    }```

and then I have the event function/class method or whatever this would be called
```js
submitClicked(event) {
        this.submitted = true;
        const next = document.getElementById("next-button");
        next.style.opacity = "100";
        next.style.cursor = "pointer";
        event.target.style.opacity = "50%";
        event.target.style.cursor = "not-allowed";

        // this.checkAnswer()
    }```

and I want to be able to call my separate class method checkAnswer() inside submitClicked, but I cannot because *this* now refers to the event target instead of the class object
winter trench
#

Quick fix is making the event handler (that's the name you've been looking for) a field

submitClicked = (event) => {
  ...
}
open ferry
#

ohhh, okay thank you guys both, I will try these 👍