简体   繁体   中英

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.

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>

Consider the example below. Define your function in the connection.done callback function, then call the function when a selection has changed.

 $(function() { // Start the connection. $(window).load(function() { // We'll define our function here postConnectFunction = function(index) { console.log('You selected', index) } }); }); // When something is changed we'll call the function above $('select').on('change', function(event) { if (postConnectFunction) { postConnectFunction(event.target.value); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> <option>Option 4</option> </select> 

You could expose the function to an outer-scoped reference, like so:

var functionReference = undefined;
$(function() {
    $.connection.hub.start().done(function() {
        functionReference = function () { /* ... */ };
    });
});

// You could then check if the function is set later, and invoke it:
if (functionReference) {
    functionReference(index);
}

However, a better way to handle this sort of problem that you are presenting would be to set the event handler instead of passing around a function reference:

<script>
$(function () {
    // Obtain a reference to the carousel element:
    var carousel = document.getElementById("mediaCarousel");

    // Start the connection.
    $.connection.hub.start().done(function () {
        window.gwd.boardSelectionChanged = function (event) {
            // Call your handler function
            handleBoardSelectionChange(carousel.currentIndex);
        };
    });

    // We are separating and naming this function so that the logic
    // above remains concise and readable, if we kept all of the
    // functions of this nature anonymous it would have been harder to
    // follow the code due to length and scope depth.
    function handleBoardSelectionChange(index) {
        // Do your work here
    }
});
</script>

<script type="text/javascript" gwd-events="handlers">
window.gwd = window.gwd || {};
gwd.boardSelectionChanged = function(event) {
    // Indicate to the user that we are not ready yet.
    // (Do whatever is sensible here, maybe doing nothing is better?)
    alert('Not connected yet, please wait...');
};
</script>
<script>
    var innerfunc;
    $(function () {
        // Start the connection.
        $.connection.hub.start().done(function () {
            // How to define some functions here to call from below script?
              innerfunc = function(index) {
                  console.log('here is my index: ' + index);
              };

        });
    });
</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( innerfunc ) innerfunc(index);
};
</script>

Make sure the top code executes first before the bottom one. If racing condition persists, you can check with,

if( innerfunc ) innerfunc(index)

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM