Reputation: 6070
I am rolling my own jQuery form validator for a project I'm working on. I am defining the type of validation required in data-validate on the input elements.
I want to check if this validation function exists in my plugin before calling it (all within the plugin itself).
Before I have used:
if($.isFunction(window['functionName']))
window['functionName']();
however this doesn't appear to work within my plugin:
(function( $ ) {
$.fn.validateForm = function(options) {
...
findInputs();
function validateRequired(input) {
}
function findInputs() {
...
if($(this).attr("data-validate"))
{
// Get list of required validation functions
var toValidate = $(this).attr("data-validate").split(/\s+/);
for(var i = 0; i < toValidate.length; i++) {
// Hardcoded function name call for testing
if($.isFunction(window['validateRequired']))
window['validateRequired']();
}
}
}
}
Upvotes: 1
Views: 158
Reputation: 2645
The best way to handle this is to declare your functions as part of an object literal. That way, you can reference the literal within your plugin, like so:
(function( $ ) {
var methods = {
validateRequired: function(input)
{
// STUB
}
};
$.fn.validateForm = function(options) {
function findInputs() {
if($.isFunction(methods['validateRequired'])) methods['validateRequired']();
}
};
});
Upvotes: 1
Reputation: 13941
Im not JS expert, but try this:
if(typeof (someFunction) == 'function') {
// do something
}
EDIT
Or like this, using function name as string:
if(typeof this["functionName"] == "function") {
this["functionName"](); //it exists, call it
}
I found this here:
javascript: how to judge a function name exists? / see Nick Craver answer.
by googling like this: "function name exists javascript"
If you are searching for something about jQuery - try to search it with javascript keyword instead of jQuery. jQuery is a framework written in javascript.
Upvotes: 0