ThePrimeagen
ThePrimeagen

Reputation: 4582

String to function javascript

Say i am using some of the html5 data chars and i want to know what function to call when say something is completed for a certain div tag.

so my data would look like

data-callback='jsAPI.aSubset.desiredFunction'

How would i convert that callback (a string) into the function that i want to call. A simple global function such as

data-callback='_myfunction'

<script>
    function _myfunction() { alert("yes my function"); }
    $("div").click(function() {
        var fn = $(this).data("callback");
        if (typeof fn === 'function') {
            fn();
        }
    })
</script>

but how do i do it with the previous one jsAPI.aSubset.desiredFunction Thanks

Upvotes: 3

Views: 4259

Answers (5)

ja_swenberg
ja_swenberg

Reputation: 21

You might want to just use Function("functionstring"). The Function function returns a function from a string.

Upvotes: 1

GregL
GregL

Reputation: 38113

Sounds like a great use case for the dreaded eval().

I would do something like:

var fnString = "jsAPI.aSubset.desiredFunction";
var fn = eval(fnString);
if (typeof(fn) === "function") {
    fn.apply();

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Using square brackets only works if you have no . chain.

Try this instead:

var elms = fn.split(".");
var curr = window;
var nxt;
while(nxt = elms.shift()) curr = curr[nxt];
curr();

Upvotes: 2

user1106925
user1106925

Reputation:

Use square brackets...

jsAPI.aSubset[fn]();

so...

if (typeof jsAPI.aSubset[fn] === 'function') {
    jsAPI.aSubset[fn]();
}

Upvotes: 1

duri
duri

Reputation: 15351

Try window[fn]() if the function is defined in the global scope.

Upvotes: 0

Related Questions