-1

I'm running an event listener on an object like below

googletag.pubads().addEventListener('slotOnload', (event) => {
    // do something
});

What I'm looking for is load googletag.pubads() via a variable value, and then the event listener should be applied on the variable. For eg:-

var x = 'googletag.pubads';

x().addEventListener('slotOnload', (event) => {
    // do something
});

Inspired from this answer, This is what I tried

function runFunction(name, arguments)
{
    var fn = window[name];
    if(typeof fn !== 'function')
        return;

    fn.apply(window, arguments);
}


var x = runFunction('googletag.pubads', [])  // this returns undefined

For the uninitiated, googletag is a package that shows ads on your page. Stackoverflow also uses googletag for displaying the ads. You may try the eventListener on Stackoverflow page console itself.

How can I fix this?? What am I doing wrong?

Praful Bagai
  • 16,684
  • 50
  • 136
  • 267
  • 4
    You would lookup `window['googletag']`, and in THAT object lookup the `pubads` member. – Tim Roberts Jun 02 '23 at 06:17
  • 1
    Why? Specifically, where are you getting this string and what are its possible values? Matters in order to not complicate the solution unnecessarily. – Ry- Jun 02 '23 at 06:26

1 Answers1

0

You can convert your x string to an actual object reference by parsing it:

// Helper function: simple parser
const getAtPath = (root, path) => path.split(".").reduce((obj, k) => obj[k], root);

// Mock for demo:
var googletag = { pubads: { addEventListener(typ, cb) { cb(); } } };

// Demo
var x = 'googletag.pubads';
getAtPath(window, x).addEventListener("", () => console.log("addEventListener called"));

This snippet just uses a very basic parser: it assumes that the input is a dot-separated list of property names.

If the dynamic name would use more extended syntax, for instance to reference array indexes with bracket notation, ...etc, then the parser needs to foresee that. See also lodash _.get

trincot
  • 317,000
  • 35
  • 244
  • 286