0

I am trying to call a public member function from a static variable this so typescript:

class myClass {
    static myTmp: myClass;

    constructor(elem: HTMLElement) {
        elem.addEventListener(“mousedown”, this.callThis);
    }
    public setTmp() {
        myClass.myTmp = this;
    }
    public callThis() {
        myClass.myTmp.myMethod();
    }
    public myMethod() {
        console.log("Hello World!");
    }
}

But I keep getting myClass.myTmp.myMethod is not a function. This example may seem weird, but it makes sense in my real problem. I have tried doing it through a global variable as well, but still no luck. I would like to keep it all within one class. Am I missing something major here?

EDIT: This is what I was trying to do, and this works:

class myClass {
    static myTmp?: myClass;

    constructor(elem: HTMLElement) {
        elem.addEventListener(“mousedown”, this.callThis.bind(this));
    }
    public setTmp() {
        myClass.myTmp = this;
    }
    public callThis() {
        myClass.myTmp?.myMethod();
    }
    public myMethod() {
        console.log("Hello World!");
    }
}

I then have a list of myClass'es and at some point "setTmp" is called, enabling the "myMethod" method.

7
  • 1
    It worked for me in the TS playground as expected. Commented Jan 2, 2021 at 16:22
  • 1
    Updated it to be closer to the actual problem Commented Jan 2, 2021 at 16:28
  • 1
    elem.addEventListener('mousedown', () => this.callThis()) Commented Jan 2, 2021 at 16:29
  • 1
    this in the event handler is the element and not the object. You can store this to a variable first and then use it. Eg: var self = this; Commented Jan 2, 2021 at 16:33
  • 1
    Ah. Thanks. I solved it by using elem.addEventListener("mousedown", this.callThis.bind(this)); instead. Commented Jan 2, 2021 at 16:36

1 Answer 1

1

why don't you simply use arrow functions?

elem.addEventListener('mousedown', () => this.callThis());

changing it to this code will work. You don't need to be using the .bind at all :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.