Last active
August 29, 2015 14:01
-
-
Save JakeCoxon/a658defea9cd2c4377b1 to your computer and use it in GitHub Desktop.
Track promises and fire event when all finish
This file contains hidden or 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 PromiseTracker(changeFunc) { | |
var tracked = []; | |
var events = []; | |
function fireOnChange(isActive) { | |
for (var i = 0; i < events.length; i++) | |
events[i](isActive); | |
} | |
function removePromise(promise) { | |
tracked.splice(tracked.indexOf(promise), 1); | |
if (tracked.length === 0) { | |
fireOnChange(false); | |
} | |
} | |
this.addPromise = function(promise) { | |
if (promise.state() != "pending") return promise; | |
tracked.push(promise); | |
promise.always(function() { | |
removePromise(promise); | |
}); | |
if (tracked.length == 1) { | |
fireOnChange(true); | |
} | |
return promise; | |
}; | |
this.numTracked = function() { | |
return tracked.length; | |
}; | |
this.onChange = function(func) { | |
events.push(func); | |
}; | |
this.onActive = function(func) { | |
events.push(function(isActive) { | |
if (isActive) { | |
func(isActive); | |
} | |
}); | |
}; | |
this.onInactive = function(func) { | |
events.push(function(isActive) { | |
if (!isActive) { | |
func(isActive); | |
} | |
}); | |
}; | |
if (changeFunc) { | |
this.onChange(changeFunc); | |
} | |
} | |
PromiseTracker.toggleElementActiveClass = function(el, className) { | |
el = $(el); | |
return function(isActive) { | |
el.toggleClass(className, isActive); | |
}; | |
}; | |
PromiseTracker.toggleElementInactiveClass = function(el, className) { | |
el = $(el); | |
return function(isActive) { | |
el.toggleClass(className, !isActive); | |
}; | |
}; |
This file contains hidden or 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
<style> | |
#loader { display:none; } | |
#loader.loading { display: block } | |
</style> | |
<div id="loader">Loading</div> | |
<button id="button">Click</button> | |
<script> | |
function timeoutPromise(time) { | |
var def = $.Deferred(); | |
setTimeout(function() { | |
def.resolve("Done"); | |
}, time); | |
return def.promise(); | |
} | |
$(function() { | |
var tracker = new PromiseTracker(PromiseTracker.toggleElementActiveClass("#loader", "loading")); | |
$("#button").click(function() { | |
tracker.addPromise(timeoutPromise(1000)); | |
tracker.addPromise(timeoutPromise(2000)); | |
}) | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment