0

I understand how to pass anonymous functions as a function parameter:

somefunction('value1',function(){alert('value2')});

But what I'm running into a problem with is if the function-as-a-parameter also has a variable inside it being used as a callback:

function FUNC(value1,callback) {
   alert(value1);
   callback();
}

function LOAD() {
// this function gets called when the page initially loads
   var UN = document.getElementById('username');
   FUNC('some value', function(){alert('user name: ' + UN.value)});
}

This produces a "ReferenceError: UN is not defined" error. I assume that is because the internals of FUNC() have no idea about the variable UN from LOAD(). How can I make this work? Use .bind, .call, .apply somewhere? I have found the following links, but are unsure if they are applicable.

Article 1

Article 2

Community
  • 1
  • 1
user1646428
  • 179
  • 2
  • 12
  • 2
    JavaScript has lexical scope. What you have should work, it does for me: https://jsfiddle.net/k4xpLw89/ . Please provide an example that actually reproduces your issue. – Felix Kling Jan 21 '17 at 18:53
  • It sounds like `document.getElementById('username');` is null. Make sure an element with `id="username"` exists. – tklg Jan 21 '17 at 18:54
  • 1
    @Villa7_: That would throw a different error though, not a `ReferenceError`. – Felix Kling Jan 21 '17 at 18:54
  • Ah, right. In that case, having just tested it, it also works for me. – tklg Jan 21 '17 at 18:59
  • This is weird... I can confirm that the fiddle also works for me, but for some reason my project continues to give me that error! Let me continue to work on the fiddle to see if I can reproduce... – user1646428 Jan 21 '17 at 19:16
  • So I've forked that fiddle to add more of the actual code, and I'm getting the reference error, but this is for the dialog() function call for some reason... [jsfiddle.net/9wvbht0f](https://jsfiddle.net/9wvbht0f/) – user1646428 Jan 21 '17 at 19:42
  • The error is generated when the 'OK' button is clicked (which should execute the callback) – user1646428 Jan 21 '17 at 19:52

1 Answers1

0

So after playing with the code for several hours, I realized that one of the functions was adding the callback like:

...snip...
HTML += "<input type='button' id='btnOK' value='OK' onClick=\"dialog("+cb2+");\" />";
...snip...

document.getElementById('test').innerHTML = HTML;

This causes problems since you can't add a function to a string. Instead the proper way was to do the following:

...snip...
HTML += "<input type='button' id='btnOK' value='OK' />";
...snip...

document.getElementById('test').innerHTML = HTML;
document.getElementById('btnOK').onclick=function(){dialog(cb1)};

I just wanted to follow-up if someone stumbled upon this SO, they would at least have the solution I found.

user1646428
  • 179
  • 2
  • 12