0

Following is a sample code created based on the scenario. showData() function is defined inside a javascript load function. I wanted to call showData() from another file maybe on a button click. I know this will work if the showData is made global. It's not possible to make the function global, as in this scenario it's a dynamically generated code. Is there anyway in JS that allows to call such functions ?

// Not possible to change the structure of this file as its coming dynamically
window.addEventListener("load", function() {
  showData(); // 1st time call
  function showData() {
    console.log('starting execution')
  }
});

// Calling from another file
showData(); // 2nd time call - not possible
mplungjan
  • 169,008
  • 28
  • 173
  • 236
theFrontEndDev
  • 890
  • 1
  • 17
  • 41

2 Answers2

1

No.

The function is declared inside another function. Its scope is that function.

Unless you change that code to make it a global, it isn't accessible from outside the containing function at all.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

If the structure of the code can't be changed, perhaps you could try attaching your function to the global window object, like:

window.addEventListener("load", function() {
  // attached to window
  window.showData = function() {
    console.log('starting execution')
  };

  window.showData(); // 1st time call
    
});

// Calling from another file
window.showData();

But make sure the second call (from the other file) has a little bit of a delay (remember the eventListener has to be attached to the window first, before the function becomes available).

You could try:

// second call
setTimeout(function() {
    window.showData();
}, 1000);
Deolu A
  • 752
  • 1
  • 6
  • 13