The question of how to make an asynchronous JSONP call has been asked a few times. In my case I require this functionality in an event queue. I'm using jQuery.bind-first in order to get my event handler to the start of the queue. I need to make a jsonp call in my handler and have the result from that call used in a subsequent user defined handler.
Edit for clarity of question: How do you make an asynchronous ajax jsonp request inside an event handler, ensuring that the rest of the event queue will not be executed until the ajax request has completed?
EDIT:
I just found this which is nearly identical. In this method events like form submission happen because the final submit event on a form which calls the action is not in the event queue.
The answer is pretty simple. Use $.event.trigger to create a new event queue, bind all event handlers past the current handler to the new event, stop propagation on the current event, on success of the jsonp call trigger the new event.
// Bind our function to the event name
$('.selector').bindFirst(evnt_nm, {}, function(e){
var that = this
// Stop all propagation from this event queue
e.preventDefault()
if (e.stopImmediatePropagation) e.stopImmediatePropagation()
if (e.cancelBubble!=null) e.cancelBubble = true
e.stopPropagation()
// Create the new my-queue event
$.event.trigger({
type: "my-queue",
message: e,
time: new Date()
});
// Copy this events queue
// Using slice(0) creates a copy instead of a reference
var events = $._data( $(this)[0] ).events[evnt_nm].slice(0)
// Remove this event from the queue
events.shift()
// Bind the event handlers to the new queue
$.each(events, function(index, event){
$(that).bind('my-queue',event.handler)
})
// Make your jsonp call
$.ajax({
// ...
success : function(data, textStatus, jqXHR){
// ...
// Trigger the rest of the events stored in the new queue once your finished.
$(that).trigger('my-queue')
}
})
return false;
})
Now when ever your event is triggered the rest of the events in the queue will not be processed until the jsonp call successfully returns.