2013-08-16 77 views
1

我已經創建了一個包含以下內容的JavaScript文件:是否可以調用嵌套在另一個函數中的函數?

(function ($) { 
    //Define a Drupal behaviour with a custom name 
    Drupal.behaviors.jarrowDynamicTextfieldValidator = { 
    attach: function (context) { 
     //Add an eventlistener to the document reacting on the 
     //'clientsideValidationAddCustomRules' event. 
     $(document).bind('clientsideValidationAddCustomRules', function(event){ 
      //Add your custom method with the 'addMethod' function of jQuery.validator 
      //http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage 
      jQuery.validator.addMethod("typeValidator", function(value, element, param) { 

      ...bunch of code here... 

      }, jQuery.format('Field can not be empty')); 
     }); 
     } 
    }; 
})(jQuery); 

我想要做的就是添加一個變化監聽器選擇框,這樣當選擇更改它會調用這個確認功能。我不確定是否可以這樣做,因爲驗證代碼被隱藏在幾個函數中。這可能嗎?

+0

哪些功能特別是你想要打電話? – Kristian

+1

是的,你絕對可以做到這一點...以許多不同的方式。檢查了這一點:http://stackoverflow.com/questions/500431/javascript-variable-scope –

回答

1

您原來的代碼顯示它的方式,不,您將無法調用任何這些功能,因爲它們是anonymous,並且在父功能的範圍內是

如果你要聲明一個變量的函數調用它的功能之外,那麼你能夠重複使用的功能,因爲這將是全球向其他功能的範圍。注意:如果您希望變量完全是全局的,或者更確切地說,無論您身在代碼中的哪個位置,都可以訪問這些變量,只是不要在變量前面寫上var,那麼它將成爲「全局」實際上相當於將變量放在window命名空間中。

這裏有這樣一個例子,使用您的代碼:

(function ($) { 

    var customCallback = function(event){ 
     //Add your custom method with the 'addMethod' function of jQuery.validator 
     //http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage 
     jQuery.validator.addMethod("typeValidator", function(value, element, param) { 

     ...bunch of code here... 

     }, jQuery.format('Field can not be empty')); 
    }; 

    //Define a Drupal behaviour with a custom name 
    Drupal.behaviors.jarrowDynamicTextfieldValidator = { 
     attach: function (context) { 
     //Add an eventlistener to the document reacting on the 
     //'clientsideValidationAddCustomRules' event. 
     $(document).bind('clientsideValidationAddCustomRules', customCallback); 
     } 
    }; 

    //now you can use that function again... 
    $('#something').on('someEvent', customCallback); 

})(jQuery); 

請注意,你必須做一些調整,該功能,以確保所有的變量都可用之類的東西,由於可變範圍。所以,這可能需要進行一些調整才能使其適用於您的場景。

+0

多麼好看的髮型。 – naomik

+0

什麼...大聲笑 – Kristian

+0

@克里斯蒂安我覺得你剛剛在這麼調情! – Mathletics

1

通常情況下,您將無法在不修改代碼的情況下調用該匿名函數,但這似乎是爲jQuery驗證插件註冊自定義驗證規則的方式,一旦註冊,您就可以使用該自定義通過插件的API來統治。

例如,下面的代碼添加自定義規則:

jQuery.validator.addMethod("typeValidator", function(value, element, param) { 

...bunch of code here... 

}, jQuery.format('Field can not be empty')); 

現在你可以初始化窗體上的插件,並調用valid函數來驗證表單。

$('#someForm').validate({ 
    rules: { 
     someField: { 
      typeValidator: true //use the custom validation rule 
     } 
    } 
}); 

現在,你可以檢查表格是否有效,使用$('#someForm').valid()

查看plugin's API瞭解更多信息。

+0

感謝您的建議。我喜歡這個解決方案,因爲它對我來說似乎更清潔我會嘗試這個和其他的解決方案,這樣我就可以建立我使用javascript的經驗。謝謝! – user5013

相關問題