Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn a String into a javascript function call (case with objects)

Tags:

javascript

Yeah, there are numerous questions like How to turn a String into a javascript function call? or How to execute a JavaScript function when I have its name as a string.

But what if we have not a plain function name, but an object property name which in fact is a function?

Like:

var callMe = 'foo.bar.baz';

and the code expected to be called is:

window.foo = {
    bar: {
        baz: function() {
            alert('Eureka!');
        }
    }
};

Why I need this: the callback parameter is passed via url and it can (by application design) be either a function name or FQN of object's property.

Any ideas others than eval()?

UPD:

My final implementation:

var parts = callbackName.split('.'),
    callback;

for (i in parts) {
    if (!callback) {
        callback = window[parts[i]];
    } else {
        callback = callback[parts[i]];
    }

    if (typeof callback === 'undefined') break;
}

if (typeof callback === 'function') {
    callback();
} else {
    console.error('Passed callback is not a valid function');
}
like image 442
zerkms Avatar asked Jan 31 '26 22:01

zerkms


2 Answers

try

window['foo']['bar']['baz']()

If this works for you, should be easy to translate 'foo.bar.baz' into that.

like image 54
Itay Moav -Malimovka Avatar answered Feb 02 '26 15:02

Itay Moav -Malimovka


See the code below and check out the fiddle ( http://jsfiddle.net/bxsHp/ ) :

window.foo = {
    bar: {
        baz: function() {
            alert('Eureka!');
        }
    }
};
//foo.bar.baz();
var callme = "foo.bar.baz";
var fn = window[callme.split(".")[0]];//get the first prop. bar
var len = callme.split(".").length;//length of obj tree
for(i=1;i < len;i++)
{//search for the next obj  
  fn = fn[callme.split(".")[i]];
}
if(typeof(fn) == "function")
{//check and call
  fn();
}
like image 31
gideon Avatar answered Feb 02 '26 13:02

gideon