【问题标题】:Accessing jquery validation variables in Typescript class在 Typescript 类中访问 jquery 验证变量
【发布时间】:2018-08-21 21:51:16
【问题描述】:

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

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

我有以下课程:

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()) 的所述示例是错误的,因为那时我无法访问类变量 errors

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

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

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

【问题讨论】:

    标签: jquery typescript jquery-validate aurelia


    【解决方案1】:

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

    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());
                }
            });
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多