简体   繁体   中英

Returning false on a function that contains another function

I'm using jquery ui and sortable, I want to combine this with an Ajax call on the change event:

$("#events").sortable({
    change: function (event, ui) {
        $.ajax({
            type: "POST",
            url: "/tasks/updateTaskUserPosition",
            dataType: "json",
            data: {
                taskId: ui.item.data("task-id")
            },
            success: function (result) {
                if (result == "error") {
                    alert("Not possible!");
                    return false;
                }
            }
        });
    }
});

I want the change event to return false (IE, reset the position change) if a condition is met on Ajax success, essentially I need to "crawl" back a function. How should I go about doing this?

How should I go about doing this?

You can't (well, not reasonably). Ajax calls are asynchronous. By the time the ajax call completes, the call sortable made to change has long-since returned.

While you could (for now) make the ajax call synchronous, that's not usually a good idea as it locks up the UI of the browser during the call. jQuery will be removing the async flag in a future version.

So the correct thing to do is not rely on the result of the ajax call in change ; come at the problem a different way (perhaps saving some state and restoring that state if required).

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