user1382306
user1382306

Reputation:

pass argument to function passed as argument to jQuery function

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

Answers (2)

Richard
Richard

Reputation: 8280

jsFiddle Demo

Setup

Firstly you'll need to setup the pleaseCallTheOtherFunction method, like so:

$.fn.pleaseCallTheOtherFunction = function(otherFunction) {
    if ($.isFunction(otherFunction)) {
        otherFunction.apply(this, ['works']);
    }
};

Usage

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);
});

Alternatively

You could write an in-line function:

$(document).ready(function () {
    $().pleaseCallTheOtherFunction(function(testIt) {
        alert(testIt);
    });
});

Upvotes: 2

the system
the system

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

Related Questions