2017-06-26 1 views
0

Ich spiele mit RequireJS herum und erstelle eine einfache Validierungsbibliothek. Ich gebe ein Objekt zurück, das voll von Funktionen ist, möchte aber, dass eine dieser Funktionen von einem Event-Handler aufgerufen wird, der von einer anderen Funktion platziert wird.Aufruf der Funktion für dasselbe Objekt aus dem Ereignis

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

Wie rufe ich die checkPageValidation() Funktion an?

Antwort

0

Sie können während der Initialisierung kein Objekt referenzieren, stattdessen einen Konstruktor erstellen und mit diesem Schlüsselwort aufrufen.

Sie können die Funktion aufrufen, indem dieses Stichwort

this.checkPageValidation(); 

ODER

Erstellen Sie eine Variable vor

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 
      } 
     } 
    } 
}); 
+1

Leider Rückkehr 'this' an diesem Punkt ist die '', die das Ereignis deshalb 'Uncaught TypeError ausgelöst: this. checkPageValidation ist keine Funktion –

+0

Edited gucke in die Änderungen –

+0

Dies geht immer noch nicht um das Problem, dass "dies" das HTML-Steuerelement ist und nicht das js-Objekt, daher 'this.validation()' nicht existiert. –

Verwandte Themen