knockout-sortable icon indicating copy to clipboard operation
knockout-sortable copied to clipboard

Question regarding cancelDrop: Perform a request

Open dmr opened this issue 12 years ago • 2 comments
trafficstars

I'd like to do a request to a server before I update my model. I can use beforeCancel for that. If I change args.cancelDrop to true the item won't be moved.

Is there a way to perform an ajax request and wait for the result before leaving the beforeMove function?

I thought about

beforeMove = function(args) {
    var xhr = $.ajax({url: 'http://example.com/update/', async: false})
    .fail(function(xhr, text_status) {
        if (xhr.status === 0) { // connection error
            args.cancelDrop = true;
        }
    });
}

but I know that $.ajax({async:false}) is not waiting for the request to finish.

Does anyone have a solution for this?

Keep up the great work, knockout-sortable is awesome!

dmr avatar Aug 23 '13 13:08 dmr

@dmr - there is not currently a way to set the cancel flag asynchronously. Seems like making jQuery do the AJAX call sync (async: false) should work, but is generally not a good practice. My best advice would be to potentially take the approach that you expect the AJAX call to succeed and let the move happen. Then, if it fails move the item back to its original index.

rniemeyer avatar Nov 16 '13 16:11 rniemeyer

Thank you for the response. Right now I solved this by the solution you proposed.

knockout-sortable could check if beforeMove returns a deferred and act accordingly, something like Durandal does (https://github.com/BlueSpire/Durandal/blob/master/src/durandal/js/composition.js#L89):

if(result && result.then) {
    result.then(successCallback);
} else if(result || result === undefined) {
    successCallback();
}

What do you think?

dmr avatar Nov 18 '13 10:11 dmr