Search code examples
javascriptcallback

Javascript nesting callback API - out of my league


I'm trying to use a callback to encapsulate an API solution as follows:

<html>
    <script>
        function main ( CB ) {
            function msg ( s ) {
                window.alert(s);
            }
            CB();
      }
    </script>
    <script>
        main( function () {
           msg("Hello universe"); // <--here
            } );
    </script>
</html>

and Javascript throws an error "msg is not defined". I see the problem, but it's not clear how to fix it. I flailed around a bit, and tried main.msg(...) and this.msg(...) at the line marked "<--here", but had similar results.


Solution

  • Basically you just needed to:

    • In the first half: pass msg into CB() --> CB(msg)
    • In the second half: get msg as a parameter from main --> main(function (msg) {...

    However since it is already a bit confusing anyway, I think having a function and a parameter later on both named msg adds potential confusion. Also there's no need for two separate <script> tags.

    Here it is cleaned up a bit, and I renamed some things to help make it more clear

    function main (callbackFn) {
      function msgFn(str) {
          window.alert(str);
      }
      callbackFn(msgFn);
    }
    
    main(function (myFunc) {
       myFunc("Hello universe");
    });