2

In a hybrid mobile app I'm working on I can't call functions or methods from external classes. I've simplified the code to just this:

var hub_api = (function() {
    function send() {
        console.log('hub api called');
    };

    return {
        send: function() {
            send();
        }
    };
});

which is called like this:

(function() {

    function register_event_handlers() {
        $(document).on(" touchend", "#btntest", function(evt) {
            hub_api.send();
            alert('pressed test button');
        });
    }

    document.addEventListener("app.Ready", register_event_handlers, false);

})();

The actual code works fine in another project. The scripts are both included like this:

<script type="application/javascript" src="js/helpers/api.js"></script>
<script type="application/javascript" src="js/helpers/testclass.js"></script>

Running the app returns hub_api is not defined. I'm completely stumped. Any help is appreciated.

Edit: I found when I put the hub_api function in app.js it works as expected but still does not when included in a separate api.js script. The scripts are called in the correct sequence.

stephen
  • 385
  • 3
  • 24

1 Answers1

0

Try defining hub_api inside the main function(), like this:

(function() {

    var hub_api = (function() {
        function send() {
            console.log('hub api called');
        };

        return {
            send: function() {
                send();
            }
        };
    })();

    function register_event_handlers() {
        $(document).on(" touchend", "#btntest", function(evt) {
            hub_api.send();
            alert('pressed test button');
        });
    }

    document.addEventListener("app.Ready", register_event_handlers, false);

})();
krisrak
  • 12,882
  • 3
  • 32
  • 46
  • your event handler code is in an isolated `(function(){...})();`, so all definitions outside cannot be accessed inside, so u have to define it inside – krisrak Jan 26 '16 at 17:49
  • That's incorrect. The hub_api when declared outside the enclosure but in the same script file works fine. It also works in different projects. It has to be how the scripts are being loaded. – stephen Jan 27 '16 at 14:28