1

I am trying to call a class method from within a click function like so:

class ClassName {
    constructor(element) {
        this.elem = element;
        this.elem.on('click', function() {
            this.notify();
        });
    }
    notify() {
        console.log("Element clicked!");
    }
}

It does not work, i think because (correct me if i am wrong) using this.notify(); in a function means that it is referring to something within the said function, rather than the class itself. My question is whether calling a class method from within the click function is possible at all? I am new to classes in general and i would appreciate advice. Is there a better way to add event listeners to elements from inside the class?

slidjoe
  • 113
  • 1
  • 6

1 Answers1

1

You can use an arrow function to stay in the same scope otherwise this won't refer to your object anymore if it is in a normal function.

class ClassName {
  constructor(element) {
    this.elem = element;
    this.elem.on('click', () => {
      this.notify();
    });
  }
  notify() {
    console.log("Element clicked!");
  }
}

new ClassName($("button"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38