less.watch.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * @file
  3. * Contains JS required for less watch functionality.
  4. */
  5. ;(function ($) {
  6. "use strict";
  7. Drupal.behaviors.less_watch = {
  8. attach: function (context, settings) {
  9. var watched_files = [],
  10. $watched_links;
  11. $watched_links = $('head link[src$=".less"]', context).each(function () {
  12. // Only grab the portion of the url up to, but not including, the '?'.
  13. watched_files.push($(this).attr('href'));
  14. });
  15. if (watched_files.length > 0) {
  16. // Modeled after example @ http://www.erichynds.com/javascript/a-recursive-settimeout-pattern/
  17. var poller = {
  18. failed_requests: 0,
  19. // starting interval in milliseconds
  20. interval: 500,
  21. // kicks off the setTimeout
  22. init: function(){
  23. setTimeout(
  24. $.proxy(this.getData, this), // ensures 'this' is the poller obj inside getData, not the window object
  25. this.interval
  26. );
  27. },
  28. // get AJAX data + respond to it
  29. getData: function() {
  30. var self = this;
  31. $.ajax({
  32. type: 'POST',
  33. url: settings.basePath + 'ajax/less/watch',
  34. data: {
  35. less_files: watched_files
  36. },
  37. // On success, reset failed request counter and update style links.
  38. success: function ( response ) {
  39. self.failed_requests = 0;
  40. $.each(response, function (index, value) {
  41. var old_file = value.old_file,
  42. new_file = value.new_file;
  43. // Math.random() at the end forces a reload of the file.
  44. $('head link[href^="' + old_file + '"]', context).replaceWith($('<link type="text/css" rel="stylesheet" media="all" />').attr('href', new_file + '?' + Math.random()));
  45. watched_files[$.inArray(old_file, watched_files)] = new_file;
  46. });
  47. },
  48. // On failure, count failed request and increase interval.
  49. error: function () {
  50. ++self.failed_requests;
  51. self.interval += 500;
  52. },
  53. // On success or failure, restart
  54. complete: function () {
  55. if( ++self.failed_requests < 10 ){
  56. self.init();
  57. }
  58. }
  59. });
  60. }
  61. };
  62. poller.init();
  63. }
  64. }
  65. };
  66. })(jQuery);