Skip to content

Instantly share code, notes, and snippets.

@atestu
Last active December 18, 2015 14:39
Show Gist options
  • Save atestu/5799104 to your computer and use it in GitHub Desktop.
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.
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);
});
}
<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