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

4
  • who say you cannot make it global? did you try window.showData = showData Commented Nov 23, 2020 at 9:08
  • @Ifaruki didn't get you ? Commented Nov 23, 2020 at 9:13
  • This might help you stackoverflow.com/questions/49616639/… Commented Nov 23, 2020 at 9:27
  • 1
    dispatchEvent(new Event('load')); I don't even want to post this as answer. Only if you are sure that the load event contains only that function call Commented Nov 23, 2020 at 15:31

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.