Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a function inside a function and call it from outside?

I've started learning JavaScript and this problem blocked me. please look at this:

<script>
    $(function () {
        // Start the connection.
        $.connection.hub.start().done(function () {
            // How to define some functions here to call from below script?
        });
    });
</script>

<script type="text/javascript" gwd-events="handlers">
    window.gwd = window.gwd || {};
    gwd.boardSelectionChanged = function(event) {
        var carousel = document.getElementById("mediaCarousel");
        var index = carousel.currentIndex;
        // how to pass this index to a function above?
};
</script>

in the first script I try to connect to the server. in the second script, user can select an image.

I want to pass the index from second script to a function inside the first one to send it to the server.

How can I define a function in first one and how to call it? thanks.

like image 674
Blendester Avatar asked Mar 09 '23 00:03

Blendester


1 Answers

You could do something like this:

<script>
    var newFunction = undefined;

    $(function () {
        // Start the connection.
        $.connection.hub.start().done(function () {
            // How to define some functions here to call from below script?
            newFunction = function(index){
                // Your function processing.
            }
        });
    });
</script>

<script type="text/javascript" gwd-events="handlers">
    window.gwd = window.gwd || {};
    gwd.boardSelectionChanged = function(event) {
        var carousel = document.getElementById("mediaCarousel");
        var index = carousel.currentIndex;
        // how to pass this index to a function above?
        if(newFunction) newFunction(index);
};
</script>
like image 79
Duc Filan Avatar answered Apr 09 '23 01:04

Duc Filan