[Vuejs]-Typescript static function isn't receiving arguments

1👍

The problem is your scoping. If you pass this as a first argument to the call method (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) your method will receive the correct input.

Working snippet:

class ReactiveFormElement {

    constructor(
        public value?: any,
        public validators: Function[] = []) { }

    public validate() {
        console.log('Sending to validator: ' + this.value);
        this.validators.forEach(validator =>
            validator.call(this, this.value));
    }
}

class Validators {

    static required(value: any) {
        console.log('Validator received: ', value);
        if (typeof value === 'undefined' || !value)
            return 'This value is required'
        else
            return null;
    }
}

const formElement = new ReactiveFormElement('foo', [Validators.required]);
formElement.validate();

Leave a comment