Last active
December 18, 2015 14:39
-
-
Save atestu/5799104 to your computer and use it in GitHub Desktop.
Manage loading states in Knockout.JS! This simple trick allows you to show loading states (spinners, etc) before your data is loaded. This is very useful when you're using APIs.
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
var YourViewModel = function () { | |
var self = this; | |
self.thing = ko.observable(''); | |
$.get('api/call', function (data) { | |
self.thing(data); | |
// thing is loaded, | |
self.loaded.thing(true); | |
// it is no longer loading | |
self.loading.thing(false); | |
}); | |
// This is where the magic happens! | |
// We create a loading+loaded object with a property for each | |
// observable in your view model | |
Object.keys(self).map(function (key) { | |
if (!self.loading) self.loading = {}; | |
if (!self.loaded) self.loaded = {}; | |
self.loading[key] = ko.observable(true); | |
self.loaded[key] = ko.observable(false); | |
}); | |
} |
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
<div data-bind="visible: !loading.thing(), html: thing()"></div> | |
<div class="loading" data-bind="visible: loading.thing()">Put a spinner in there</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment