3

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

5 Answers 5

4

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();
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

Use square brackets...

jsAPI.aSubset[fn]();

so...

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

7 Comments

I said the item was a string... Your just calling the function in the string as if i can magically just know what to call.
I should clarify that all you need/want in the data-callback attribute is the actual function name desiredFunction. If you can't know the object nesting beforehand, then you'd want something like @Kolink's answer.
@Michael: Why would it be magic to know beforehand which subset will be used?
yes i know. I wont know the object nesting before hand. Else i would of done the solution i provided for in my question (which is what you did).
@Michael: The solution provided in the question wouldn't work at all, because fn would be a string.
|
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.