Reputation: 5976
How do you detect if a function is a method for a jQuery element?
For example, $.fn.fadeIn
is a function:
typeof $.fn.fadeIn === 'function' //true
However, I need a way to distinguish it from a regular non-jQuery method. The goal is to be able to pass a function as a parameter and then call the function correctly.
Below is an example using a function called doIt
that takes a jQuery element and a function to be applied to the element.
Example HTML:
<h1>jQuery Function Test</h1>
<p class=t1>Highlight this line.</p>
<p class=t2>Hide this line.</p>
Example JavaScript:
function doIt(elem, func) {
if (func === 'a jQuery function') //possible?
func.apply(elem);
else
func(elem);
}
function highlight(elem) {
elem.css('background-color', 'gold');
}
doIt($('p.t1'), highlight);
doIt($('p.t2'), $.fn.fadeOut);
Line #2 of the JavaScript needs help.
Interactive version:
Upvotes: 4
Views: 145
Reputation: 374
Here’s a solution that combines the string parameter idea, checking if the method exists on the object, and support for parameters...
function doIt(elem, func, params) {
if (typeof func === 'function')
func.apply(elem, [elem].concat(params));
else if (elem[func] && params instanceof Array)
elem[func](params[0], params[1], params[2]);
else if (elem[func])
elem[func](params);
}
or on jsfiddle
Upvotes: 1
Reputation: 27247
No. But you can remove the if statement entirely:
function doIt(elem, func) {
func.apply(elem);
}
function highlight() {
this.css('background-color', 'gold');
}
doIt($('p.t1'), highlight);
doIt($('p.t2'), $.fn.fadeOut);
If you want to pass more arguments around, here's a quick example:
function doIt(elem, func) {
var args = Array.prototype.slice.call(arguments, 2);
func.apply(elem, args);
}
function highlight(color) {
this.css('background-color', color);
}
doIt($('p.t1'), highlight, 'gold');
doIt($('p.t2'), $.fn.fadeOut);
Upvotes: 3