Reputation: 36964
I created a jquery function, but $.isFunction seems to always return false if the function name is inside a string.
(function( $ ) {
$.myTest = function() {
return true;
}
})( jQuery );
alert($.isFunction('$.myTest'));
Fiddle : here.
Note : if I remove quotes (eg. alert($.isFunction($.myTest));
, it works, but my function is inside a string.
This function name is inside a string because I create a plugin to make ajax from parameters inside the dom elements. For example :
data-route="xxx.php"
data-lock=".buttonsToLock"
data-output="#outputContainer"
data-callback-after="$.myTest"
But I am unable to check if data-callback-after
is an existing function.
Any idea?
Thanks
Upvotes: 0
Views: 501
Reputation: 145408
You should always pass an object to $.isFunction()
method:
alert($.isFunction($.myTest));
Otherwise, you will always receive false
, since string is not a function by default.
Upvotes: 6
Reputation: 11955
Functions will be stored in window
so you could try something like this:
$.isFunction(window['myTest']);
But, since you are using "namespaces" you need to do it like this:
$.isFunction(window['$']['myTest']);
Or you can use this function:
function isFunctionByName(functionName, context) {
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return $.isFunction(context[func]);
}
alert(isFunctionByName("$.myTest", window));
Upvotes: 2
Reputation: 40535
Looks like you trying to dynamically call functions / callbacks.
You should consider the following approach.
(function( $ ) {
window.myTest = function() {
return true;
}
})( jQuery );
var data-route="xxx.php",
data-lock=".buttonsToLock",
data-output="#outputContainer",
data-callback-after="myTest";
// To run the function
window[data-callback-after]();
// To test the function
$.isFunction(window[data-callback-after]);
Upvotes: 1