Last active
March 27, 2017 09:06
-
-
Save gilbert/0cfa65ce832ce35a278e to your computer and use it in GitHub Desktop.
Global AJAX loading indicator for Mithril.js
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 () { | |
// | |
// Global ajax loaders | |
// | |
// This is useful for showing a loading animation, yet still taking | |
// advantage of the default behavior of m.request, which is to wait | |
// for all requests to complete before rendering the view. | |
// | |
// The loader is assumed to already be on the page | |
var loader = document.querySelector('.ajax-loader') | |
m.onLoadingStart = function () { loader.style.display = 'block' } | |
m.onLoadingEnd = function () { loader.style.display = 'none' } | |
// Monkey-patch m.request to display ajax loader when necessary | |
var originalRequest = m.request | |
var pendingCount = 0 | |
m.request = function () { | |
if (pendingCount === 0) m.onLoadingStart() | |
pendingCount += 1 | |
var promise = originalRequest.apply(null, arguments) | |
promise.then(function() { | |
pendingCount -= 1 | |
if (pendingCount === 0) m.onLoadingEnd() | |
}) | |
return promise | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment