TPL
TPL

Reputation: 179

Add loading image when use getJSON

When a page is loaded, script will call api to get list data.

function AccountTypeViewModel() 
{
    var self = this;
    self.list = ko.observableArray();
    self.selectedItems = ko.observableArray();
    var baseUri = 'url';
    $.getJSON(baseUri, self.list);
}

ko.applyBindings(new AccountTypeViewModel());

When I use this method getJSON, it will mapping data from server to self.list. How to I use callback method to binding? I use dynamic binding. I want to show image loading util getJSON is done.

Thanks in advance..

Upvotes: 2

Views: 1362

Answers (3)

Void Ray
Void Ray

Reputation: 10209

Here is the "trick" I often use:

$(document).on({
    ajaxStart: function() { $("body").addClass("loading");},
    ajaxStop: function() { $("body").removeClass("loading");}    
});

Then simple CSS:

.processing {
    display:    none;
    position:   fixed;
    z-index:    1000000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, .8 ) 
                url('/img/ajax-loader.gif') 
                50% 50% 
                no-repeat;
}

body.loading {
    overflow: hidden;   
}

body.loading .processing {
    display: block;
}

And add the div:

<div class="processing"><!-- Place at bottom of page --></div>

This way, you'll show/hide the "loading" animation for every AJAX call.

Upvotes: 1

Robert Slaney
Robert Slaney

Reputation: 3722

You are calling $.getJSON with the observableArray function as the success callback. The fact that it sets your observable value is because KO only expects 1 argument and ignore the remaining arguments.

You should supply a success function, or (preferrable) use the jQuery promise.

$.getJSON( baseUri )
  .done( function(data, status) {
    self.list(data);
  })
  .always( function() {
    // Will be called on either success or failure
    // Clear loading image here
  });

Upvotes: 2

mohsen dorparasti
mohsen dorparasti

Reputation: 8415

you should do it this way :

function AccountTypeViewModel() 
{
   var self = this;
   self.list = ko.observableArray();
   self.selectedItems = ko.observableArray();
   var baseUri = 'url';
   displayLoadingImg(); // display loading image
   $.getJSON(baseUri, function(data){ // callback
      self.list(data); // bind data
      hideLoadingImg(); // hide loading image
   });
}

read more here

Upvotes: 1

Related Questions