从事件中调用同一对象上的函数

时间:2017-06-26 15:17:15

标签: javascript requirejs

我正在玩RequireJS并创建一个简单的验证库。我正在返回一个充满函数的对象,但是希望从另一个函数放置的事件处理程序中调用这些函数之一。

define(['jquery'], function($) {
    return {
        ...
        checkPageValidation: function(){
            //Check page validation, enable/disable submit button
            ...
        },
        addValidationToControl: function(controlId, validatingFunction, comparisonControlId){
            //Add the validation function to the focus out event
            var $control = $("#" + controlId);
            ...
            $control.focusout(function (evnt){
                let $this = $(this); //this is the control that fired the event
                if(validatingFunction($this.val()){
                    ...
                } else {
                    ...
                }
                checkPageValidation(); //How to call this function?
            }
        }
    }
});

如何调用checkPageValidation()功能?

1 个答案:

答案 0 :(得分:0)

初始化时无法引用对象,而是创建一个构造函数并在其中使用此关键字进行调用。

您可以使用关键字

来调用该功能
this.checkPageValidation();


在返回

之前创建变量
define(['jquery'], function($) {
       var validation = function(){
            //Check page validation, enable/disable submit button
            ...
        };
    return {
        ...
        checkPageValidation: validation,
        addValidationToControl: function(controlId, validatingFunction, comparisonControlId){
            //Add the validation function to the focus out event
            var $control = $("#" + controlId);
            ...
            $control.focusout(function (evnt){
                let $this = $(this); //this is the control that fired the event
                if(validatingFunction($this.val()){
                    ...
                } else {
                    ...
                }
                validation(); //call using this keyword
            }
        }
    }
});