emphaticsunshine emphaticsunshine - 1 month ago 5
Javascript Question

Namespaced callback function

I have following scenario



Then I have function which checks following condition:

var callback = $input.data('callback');
if(callback){
// I want to do something like this:
window[callback].call(this);

}


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

Answer

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

foo = {
  bar: {
    baz: function() {
      console.log("foo.bar.baz()");
    }
  }
};

"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.