如何在事件队列中进行异步jsonp调用

How to make an asynchronous jsonp call in an event queue

本文关键字:异步 jsonp 调用 事件队列      更新时间:2023-09-26

关于如何进行异步JSONP调用的问题已经问过几次了。在我的例子中,我需要在事件队列中使用此功能。我使用jQuery。绑定优先,以便使事件处理程序到达队列的开头。我需要在我的处理程序中进行jsonp调用,并在随后的用户定义处理程序中使用该调用的结果。

为使问题更清晰而编辑:如何在事件处理程序中发出异步ajax json请求,并确保在ajax请求完成之前不会执行事件队列的其余部分?

编辑:
我刚找到了这个,几乎是一样的。在这个方法中,表单提交等事件的发生是因为调用该动作的表单上的最终提交事件不在事件队列中。

答案很简单。使用.event美元。触发创建一个新的事件队列,将所有事件处理程序绑定到新事件,在当前事件上停止传播,在jsonp调用成功时触发新事件。

// 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;
})

现在,当您的事件被触发时,队列中的其他事件将不会被处理,直到jsonp调用成功返回。