2013-08-16 75 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

相关问题