Created
January 31, 2018 17:57
-
-
Save carlohcs/c48f094801b4664c9f0186f55cf87f42 to your computer and use it in GitHub Desktop.
Exemplo de loading state com Promises
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
| // Método Ajax | |
| function getData(){ | |
| $promise = $.Deferred(); | |
| setTimeout(function(){ | |
| $promise.resolve(); | |
| }, 3000); | |
| return $promise.promise; | |
| } | |
| $promiseGetData = getData(); | |
| var | |
| loadingHelper = function() { | |
| return { | |
| /** | |
| * Insere um "loading" na página | |
| * | |
| * @param {jQuery.Deferred} promise O "loading" será removido apenas após | |
| * o sucesso ou falha dessa promise | |
| * | |
| * @param {String|jQuery} container O local onde o "loading" será | |
| * inserido | |
| * @return {void} | |
| */ | |
| handle: function(promise, container) { | |
| var | |
| loadingClass = 'loading-helper', | |
| animate, | |
| $loading; | |
| if (!container) { | |
| container = app.$container; | |
| } | |
| /** | |
| * Faz a animação do loader | |
| * | |
| * @return {void} | |
| */ | |
| animate = function() { | |
| // Se a promise já não estiver 'pending' não faz nada | |
| if (promise.state() !== 'pending') { | |
| return; | |
| } | |
| $loading = $(container).children('.' + loadingClass); | |
| if (!$loading.length) { | |
| $loading = $('<div class="' + loadingClass + '"><i class="icon"></i></div>'); | |
| } | |
| $loading.prependTo(container); | |
| // Fade in/out com CSS3 | |
| $loading.addClass('init'); | |
| promise.always(function() { | |
| $loading.removeClass('init').addClass('destroy'); | |
| setTimeout(function() { | |
| $loading.remove(); | |
| }, 250); | |
| }); | |
| }; | |
| /* | |
| * Coloca a animação | |
| * Delay de 1 segundo | |
| */ | |
| setTimeout(animate, 1e3); | |
| } | |
| }; | |
| }; | |
| loadingHelper().handle($promise, $('body')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment