a bit new to knockout just trying to figure out how to show a loading a div while a ko computed function is running. I'm not quite sure exactly what I need maybe I need to use knockout extenders?
Anywhere here is the fiddle.
http://jsfiddle.net/zf5k9rxq/10/
html
<input data-bind="value: val" />
<p><span data-bind="text: comp"></span>
</p>
<div data-bind="if: showloading">Loading...</div>
Javascript
function model() {
var self = this;
self.val = ko.observable("hello");
self.showloading = ko.observable(true);
this.comp = ko.computed(function () {
//show loading
this.showloading(true);
// begin long running function
var i = 0;
var j = 0;
while (i < 100000) {
i++;
j = 0;
while (j < 80000) {
j++;
}
}
// end long running function
//hide loading and return
this.showloading(false);
return this.val().toUpperCase();
}, this);
}
var mymodel = new model();
$(document).ready(function () {
ko.applyBindings(mymodel);
});
I'm not sure why you need Show/Hide
div in computed may be its a mock up of ajax call i believe .
You can achieve it by something like this . Check the commented lines in below code to see minor changes I've made .
view:
<input data-bind="value: val" />
<p><span data-bind="text: compute,visible:!showloading()"></span></p> /*Toggling span visibility if loader is running*/
<div data-bind="if: showloading">Loading...</div>
viewModel:
function model() {
var self = this;
self.val = ko.observable("hello");
self.showloading = ko.observable(true);
self.compute = ko.observable();
ko.computed(function () {
var val = self.val(); //Creating a subscription
//show loading
self.showloading(true);
setTimeout(function () { //Delaying execution to show Loader
self.showloading(false);
self.compute(val ? val.toUpperCase() : val) //Assigning value to observable inside computed .
}, 3000)
});
}
$(document).ready(function () {
ko.applyBindings(new model());
});
PS:You can make use of subscribe too if you want to avoid computed.
working sample goes here
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments