Created
May 9, 2012 08:39
-
-
Save raultm/2643036 to your computer and use it in GitHub Desktop.
Little jQuery plugin to prevent new load or abort previous one
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($, window, undefined){ | |
var requests = {} | |
$.fn.loadContent = function(url, opts){ | |
/* | |
* | |
* Customization | |
* | |
*/ | |
var defaults = { | |
loadingClass : 'loading', | |
loadingSelector : '', | |
stopCurrentAction : false, | |
} | |
var options = $.extend(defaults, opts || {}) | |
/* | |
* | |
* Ways to load content | |
* If action is taking place | |
* - Don't run the new load | |
* - Abort the current load and launch the new | |
* | |
*/ | |
var loadPreventingFlood = function(element, url){ | |
if( !isLoadClassActive(element) ){ | |
loadFunction(element, url) | |
}else{ | |
console.log('Flood Prevented') | |
} | |
} | |
var loadStoppingActiveLoad = function(element, url){ | |
if( requests[element] ){ | |
requests[element].abort() | |
} | |
loadFunction(element, url) | |
} | |
/* | |
* | |
* Load with extras | |
* | |
*/ | |
var loadFunction = function(element, url){ | |
var $element = $(element) | |
setLoadClass(element) | |
requests[element] = | |
$.get( | |
url, | |
function(resp){ | |
$element.html(resp) | |
unsetLoadClass(element) | |
} | |
); | |
} | |
/* | |
* | |
* Manage Loading Class | |
* | |
*/ | |
var setLoadClass = function(element){ | |
if(options.loadingSelector) | |
$(options.loadingSelector).addClass(options.loadingClass) | |
else | |
$(element).addClass(options.loadingClass) | |
} | |
var unsetLoadClass = function(element){ | |
if(options.loadingSelector) | |
$(options.loadingSelector).removeClass(options.loadingClass) | |
else | |
$(element).removeClass(options.loadingClass) | |
} | |
var isLoadClassActive = function(element){ | |
if(options.loadingSelector) | |
return $(options.loadingSelector).hasClass(options.loadingClass) | |
else | |
return $(element).hasClass(options.loadingClass) | |
} | |
/* | |
* | |
* jQuery Chain | |
* | |
*/ | |
return this.each(function(index, element){ | |
console.log(element) | |
if(options.stopCurrentAction) | |
loadStoppingActiveLoad(element, url) | |
else | |
loadPreventingFlood(element, url) | |
}) | |
} | |
})(jQuery, window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment