khoailang
khoailang

Reputation: 734

JavaScript callback function

please help I have a simple example here

<script type="text/javascript" language="javascript">
    function test(callback1) {
        callback1();
    }
    var f1 = function () {
        alert(1);
    }
</script>

Currently, parameter of the test function is a function, when abc button is clicked, test function will be called and then test will call f1. Everything okie with me.

However, I'd like a small change like this: parameter of the test function will be a string, I mean it should be a function name, test('f1') instead of test(f1). Is it possible?How can I implement this?

Thanks

Upvotes: 0

Views: 2762

Answers (4)

gertas
gertas

Reputation: 17145

window[callback1]();

Depending on use I would prefer prepare separate functions map.

var funcMap = {
   f1: function() {...},
   ...
};
funcMap['f4'] = function() {...};
function test(callback1) {
    funcMap[callback1]();
}

It definitely doesn't bloat window namespace and is more secure (window has more methods provided by browser).

Don't use eval - it's evil!

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227180

eval() is unneeded here. To pass a callback, just pass the function name. Functions are variables.

For example:

function test(a){
    alert(a);
}

function callback(b,a){
    b(a);
}

callback(test, 'dog'); //alerts 'dog'

So, in your code, test(f1) will work fine.

Upvotes: 2

Lukas Eder
Lukas Eder

Reputation: 220762

write something like

function test(callback1) {
    eval(callback1 + "()");
}

then callback1 should be a string

Upvotes: 0

Mahesh Velaga
Mahesh Velaga

Reputation: 21991

You can use eval() to execute the function which is passed as a string. But its deprecated to use eval.

Example:

function test(someFunctionName) {
        eval(someFunctionName);
    }

Upvotes: 0

Related Questions