在 Typescript class 中访问 jquery 验证变量

Accessing jquery validation variables in Typescript class

目前我面临以下问题,希望有人能帮助我:

我正在使用 TypeScript 开发 aurelia-cli 应用程序。 aurelia-validation 在我看来不是那么好而且太复杂了。所以我正在使用 jQuery-Validation.

我有以下 class:

export class RegistrationForm{
    @bindable errors: string[];

    public attached(){
        let validator = $("#registration-form").validate({
            onfocusout: function (element) {
                $(element).valid();
            },
            errorPlacement: function(error, element){
                this.errors.push(error.text());
            }
        });
    }
}

以及以下模板:

<template>
  ...
  <ul if.bind="errors">
     <li repeat.for="error of errors">
         ${error}
     </li>
  </ul>
...
</template>

我知道,上述 this.errors.push(error.text()) 的示例是错误的,因为在这一点上我无法访问 class 变量 errors.

现在我的问题是,是否有可能将 error.text() 信息传输到 class 变量以便在前端列出文本?

我的目标是,每次当用户更改字段 (onfocusout) 时,相应的字段都会得到验证,并在页面顶部显示一条消息。显示应该与 aurelia 绑定一起工作。

有没有人知道如何解决这个问题?

将您的 function() 更改为 arrow functions =>,因为它们保留了它们声明的范围,因此 this 指的是 class 而不是函数。

export class RegistrationForm{
    @bindable errors: string[];

    public attached(){
        let validator = $("#registration-form").validate({
            onfocusout: (element) => {
                $(element).valid();
            },
            errorPlacement: (error, element) => {
                this.errors.push(error.text());
            }
        });
    }
}