1

I am currently building something in JS and have run into the following scenario:

// these are set programmatically, not like this, just using as an example
var data = {'someData':'blah'};
var widget = 'NameOfWidget';
var command = 'someFunctionName';

// there is a base object that has all widgets and their commands as child objects
// format would be like: UBER.WidgetName.command(data);
// here is how I have tried to call it thus far
UBER[widget][command](data);
window['UBER'][widget][command](data);

I feel like I am close to figuring it out, just need a little help in figuring out exact syntax! Thanks!

spelley
  • 561
  • 1
  • 4
  • 13
  • http://stackoverflow.com/questions/912596/how-to-turn-a-string-into-a-javascript-function-call – ScottE May 08 '12 at 12:11
  • Tell me what `var_dump(UBER.widget.command)` gives you? – Starx May 08 '12 at 12:15
  • All of those attempts are correct syntax, assuming that your `UBER` object is structured like that. So if it's not working, clearly your object is not structured like that. Try doing a `console.log(UBER)` in something like the Chrome developer console, and explore that object a bit to see what it's like inside. If you still can't figure it out, report back what you see after the `console.log` – LukeGT May 08 '12 at 12:23

2 Answers2

0

Is there a reason you're not doing this?

window[UBER.widget.command](data);

Edit: I see what you're trying to do, this answer is currently incorrect should work, given that I understand what you're attempting to do.

Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
0

Try:

UBER['widget']['command'](data); 
window['UBER']['widget']['command'](data);

or

UBER.widget.command(data);
window.UBER.widget.command(data);

This assumes command is a function, widget and UBER are objects, and window['UBER'] = UBER.

When you are referencing object properties using bracket syntax, you need to use a string. If using . syntax, you must use a legal string literal that is not a reserved word in Javascript.

For example:

var command = function(){return 5},
    widget = {},
    UBER = {};
UBER.widget = widget;
widget.command = command;
console.log(UBER['widget']['command']()); // prints 5 to Chrome's developer console or firebug
AlexMA
  • 9,842
  • 7
  • 42
  • 64