Running a custom function - settings.func is not a function
I have written a jQuery plugin which I want to call a custom function on like so...
(function($) {
$.fn.testPlugin= function(options) {
var settings = {
func: null
};
if (options) {
$.extend(settings, options);
}
settings.func();
};
})(jQuery);
In this case I want to run the doSomething
function.
$(document).ready(function(){
$('div').testPlugin({
func: 'doSomething'
});
});
function doSomething() {
alert('hello');
}
I always get the error settings.func is not a function
so I am having to 开发者_如何学运维use:
eval(settings.func+"()");
Intead of:
settings.func();
Which is not ideal! Any ideas why I am getting this?
Because you're assigning a string to settings.func
, not a function. Strings are never functions, even if they contain the name of a function.
Functions are first-class citizens, however, which means you can use them as you would any other variable, assigning them to variables or passing them as arguments to other functions. Change:
$('div').testPlugin({
func: 'doSomething'
});
to
$('div').testPlugin({
func: doSomething
});
and it should work.
精彩评论