emphaticsunshine emphaticsunshine - 1 year ago 96
Javascript Question

Namespaced callback function

I have following scenario

Then I have function which checks following condition:

var callback = $input.data('callback');
// I want to do something like this:


But I can't do that because of namespacing. What is best practice for this scenario?

Answer Source

Split on ".", resolve each segment starting with window, and invoke with ():

foo = {
  bar: {
    baz: function() {

"foo.bar.baz".split(".").reduce((o, n) => o[n], window)();

Note: For simplicity, I've used Array.prototype.reduce(). For older browsers, there's a polyfill available.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download