Reputation:
Passing function name as a parameter to another function doesn't seem to work for me.
I've tried every variation from every article I can find. Currently, I have this in one js file:
function callThisPlease (testIt){
alert(testIt);
}
$(document).ready(function () {
$.fn.pleaseCallTheOtherFunction('callThisPlease');
});
I have this in another:
$(document).ready(function () {
$.fn.pleaseCallTheOtherFunction = function(functionName){
window[functionName].apply('works');
}
});
chrome console says Uncaught TypeError: Cannot call method 'apply' of undefined
.
Please help. Many thanks in advance!
Upvotes: 1
Views: 244
Reputation: 8280
Firstly you'll need to setup the pleaseCallTheOtherFunction
method, like so:
$.fn.pleaseCallTheOtherFunction = function(otherFunction) {
if ($.isFunction(otherFunction)) {
otherFunction.apply(this, ['works']);
}
};
Then you'll want to create your 'replace' function (delegate), and then call it without quotes, like so:
function callThisPlease (testIt){
alert(testIt);
}
$(document).ready(function () {
$().pleaseCallTheOtherFunction(callThisPlease);
});
You could write an in-line function:
$(document).ready(function () {
$().pleaseCallTheOtherFunction(function(testIt) {
alert(testIt);
});
});
Upvotes: 2
Reputation: 9336
If the method is undefined on window
, that means your function isn't global. Make it a global function.
Also, you can get rid of .apply
. Currently you're passing 'works'
as the this
value.
window[functionName]('works');
Upvotes: 3