1

I am new with typescript. Trying to create an abstract class for html form. I want to execute some custom code on form submit. Therefore, assigning a function to this.onsubmit. Problem is, the submit method requires the first parameter to be "this" but I need "this" to access class members as well.

export abstract class AbstractForm {
 protected form: HTMLFormElement;

 constructor(form: HTMLFormElement) {
    this.form = form;
    this.form.onsubmit = this.Submit;
 }

 private Submit(this: HTMLElement, ev: Event) {
    if (this.PreSubmissionValidation()) { // Error
        // Some code
    }
    ev.preventDefault();
 }
 abstract PreSubmissionValidation(): boolean;
 abstract OnSuccess(): any;
 abstract OnError(): any;
}
2
  • What about just binding? this.form.onsubmit = this.Submit.bind(this);? I advise against calling your first parameter this - very confusing, as it's not the value of this in the context of AbstractForm. Commented Mar 25, 2018 at 15:04
  • 1
    I'm really curious why there's has a parameter that HAS to be called this... ? What tech lead is gonna let this happen? Commented Mar 26, 2018 at 5:41

1 Answer 1

3

Could do something ugly like this instead:

private readonly Submit = (() => {
    const instance = this;
    return function (this: HTMLElement, ev: Event) {
        if (instance.PreSubmissionValidation()) {

        }
    }
})();
Sign up to request clarification or add additional context in comments.

6 Comments

"this" is brilliant.
Works perfectly.
This won't work actually, this parameters are removed by the TypeScript compiler. See my answer.
@Tao: I checked the compiled code, it works just fine.
Yeah, you're right, sorry... I shouldn't be posting today, second mistake from my side already...
|

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.