0

I'm writing an extension for a web-based texteditor. Because of the class hierarchy, my code gives some strange results.

I've tried moving the "validate" function to the base class but to no avail

class BaseClass{
    close(): void {
        // Does some stuff
    }
    save(): void {
        // Also does things
    }
}
class SubClass extends BaseClass{
    close(): void {
        this.validate(() => super.close()) // This works as expected
    }
    save(): void {
        this.validate(() => super.save()) // This throws the error: Uncaught TypeError: this.validate is not a function
    }
    validate(callback: () => void){
        // Does some validation, then
        if (validationOk) callback()
    }
}

The expected result is that both the save and close functions in the SubClass call the validate function without errors.

Dries Geenen
  • 582
  • 5
  • 14
  • Your code does not compile? – Murat Karagöz Jun 26 '19 at 12:37
  • `SubClass` has no relationship to `BaseClass`... What makes you think it's a subclass. – spender Jun 26 '19 at 12:37
  • The code does compile, but when run in a browser it gives errors in the console. For the relation between the classes: I forgot to type the extends statement in my example. It's there in the actual code – Dries Geenen Jun 26 '19 at 12:42
  • 3
    So why does this print "base save" in the console? https://codesandbox.io/s/autumn-pond-eumf7?fontsize=14&module=%2Fsrc%2Findex.ts Something else is going on here. – spender Jun 26 '19 at 12:46
  • Possible duplicate of [TypeScript "this" scoping issue when called in jquery callback](https://stackoverflow.com/questions/20627138/typescript-this-scoping-issue-when-called-in-jquery-callback) – Aleksey L. Jun 26 '19 at 13:27

1 Answers1

0

Turns out the events were initialized wrong.

I've replaced the following:

this.saveButton.addEventListener('click', this.save);

With:

this.saveButton.addEventListener('click', () => this.save());

The only reason it worked before adding the validate function, is because there is no reference to "this" in the BaseClass.save function.

Dries Geenen
  • 582
  • 5
  • 14