简体   繁体   中英

$.getJSON function executed after everything else

I'm using the following code:

function eventListenerTest(event) {
    if (document.getElementById('gem_cvo_select_list')) {
        var address;
        $.getJSON(url, function (data) {
            address = data.rows[0];
            alert("This gets executed afterwards");
        });
        alert("This gets executed first");
        event.infoWindowHtml = "<b>Address: </b>" + address;
    }
}

Problem is the $.getJSON function gets executed after the 'address' variable is used in the infoWindow. Modified the code like this:

function eventListenerTest(event) {
    if (document.getElementById('gem_cvo_select_list')) {
        var address;
        $.getJSON(url, function (data) {
            address = data.rows[0];
            event.infoWindowHtml = "<b>Address: </b>" + address;
        });
    }
}

The 'event' object doesn't seem to be accessible this way (nothing is displayed in the Google Maps infoWindow). I figured I should be able to pass 'event' to the function inside the JSON but I have no idea how to accomplish this.

Try this:

function eventListenerTest(event, callback) {
    if (document.getElementById('gem_cvo_select_list')) {
        var address;
        $.getJSON(url, function (data) {
            address = data.rows[0];
            event.infoWindowHtml = "<b>Address: </b>" + address;
            callback();
        });
    }
}

Then:

eventListenerTest(event, function(){
     // you will use updated event object here
});

You should use $.proxy method to make sure that the callback function that gets executed keeps the context of the function creating the Ajax call.

Updated Javascript:

function eventListenerTest(event) {
    if (document.getElementById('gem_cvo_select_list')) {
        var address;
        $.getJSON(url, $.proxy(function (data) {
            address = data.rows[0];
            event.infoWindowHtml = "<b>Address: </b>" + address;
        },this));
    }
}

More information: http://api.jquery.com/jQuery.proxy/

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