/client/scripts/jquery.ajaxq.js

https://bitbucket.org/biern/chorobomierz · JavaScript · 63 lines · 30 code · 12 blank · 21 comment · 13 complexity · f236be79d74e09815a9c0b2b36504aed MD5 · raw file

  1. /*
  2. * jQuery AjaxQ - AJAX request queueing for jQuery
  3. *
  4. * Version: 0.0.1
  5. * Date: July 22, 2008
  6. *
  7. * Copyright (c) 2008 Oleg Podolsky (oleg.podolsky@gmail.com)
  8. * Licensed under the MIT (MIT-LICENSE.txt) license.
  9. *
  10. * http://plugins.jquery.com/project/ajaxq
  11. * http://code.google.com/p/jquery-ajaxq/
  12. */
  13. jQuery.ajaxq = function (queue, options)
  14. {
  15. // Initialize storage for request queues if it's not initialized yet
  16. if (typeof document.ajaxq == "undefined") document.ajaxq = {q:{}, r:null};
  17. // Initialize current queue if it's not initialized yet
  18. if (typeof document.ajaxq.q[queue] == "undefined") document.ajaxq.q[queue] = [];
  19. if (typeof options != "undefined") // Request settings are given, enqueue the new request
  20. {
  21. // Copy the original options, because options.complete is going to be overridden
  22. var optionsCopy = {};
  23. for (var o in options) optionsCopy[o] = options[o];
  24. options = optionsCopy;
  25. // Override the original callback
  26. var originalCompleteCallback = options.complete;
  27. options.complete = function (request, status)
  28. {
  29. // Dequeue the current request
  30. document.ajaxq.q[queue].shift ();
  31. document.ajaxq.r = null;
  32. // Run the original callback
  33. if (originalCompleteCallback) originalCompleteCallback (request, status);
  34. // Run the next request from the queue
  35. if (document.ajaxq.q[queue].length > 0) document.ajaxq.r = jQuery.ajax (document.ajaxq.q[queue][0]);
  36. };
  37. // Enqueue the request
  38. document.ajaxq.q[queue].push (options);
  39. // Also, if no request is currently running, start it
  40. if (document.ajaxq.q[queue].length == 1) document.ajaxq.r = jQuery.ajax (options);
  41. }
  42. else // No request settings are given, stop current request and clear the queue
  43. {
  44. if (document.ajaxq.r)
  45. {
  46. document.ajaxq.r.abort ();
  47. document.ajaxq.r = null;
  48. }
  49. document.ajaxq.q[queue] = [];
  50. }
  51. }