Knockout : Async call not finished before ko.applyBindings(). Best, and easiest practice ?

- 1 answer

Ad

i KNOW this question probably has been asked here before, but i just cannot seem to get any "best practice" which.. me as a newbie, can relate to in a easy understandable way...

Knockout Code

$(document).ready(function() {

function viewModel() {

    var self = this;
    self.contacts = ko.observableArray();

        $.ajax({
            type: "POST",
            url: "ClubWebServices.asmx/GetContacts",
            data: "{'abc':'" + 123 + "'}", // if ur method take parameters
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                var contactData = data.d;
                console.log("Nr 1: " + contactData);
                self.contacts(contactData);

                console.table(self.contacts());
            },
            dataType: "json",
            failure: function(error) {
                console.log(error);
            }
        });

    console.table("Nr 2: " + self.contacts());

    ko.applyBindings(new viewModel());

}

Result is that the console.log Nr 2 is called before Console.log nr 1..

So.. how do i solve this without creating a hierarky structure where i have to implement DataService layer's which uses OnSuccess and onFailure events ?

Ad

Answer

Ad

Here are some thoughts.

  1. You're trying to create an instance of viewModel from within the function's declaration, this could lead to issues with the ko bindings.
  2. Another note, is your references to self in the success callback may not be what you think it is. Using the debugger would give you clarity on that.

I would try rearranging some things like this:

$(document).ready(function() {

  var viewModel = function (contactData) {
    var self = this;
    self.contacts = ko.observableArray(contactData);
  }

  $.ajax({
    type: "POST",
    url: "ClubWebServices.asmx/GetContacts",
    data: "{'abc':'" + 123 + "'}", // if ur method take parameters
    contentType: "application/json; charset=utf-8",
    success: function (data) {
      var contactData = data.d;
      console.log("Nr 1: " + contactData);

      ko.applyBindings(new viewModel(contactData));
    },
    dataType: "json",
    failure: function(error) {
      console.log(error);
    }
  });  

}

Changes: I close your viewModel declaration before the ajax request, and I'm passing in the contactData to the new viewModel constructor.

Also, creating a jsfiddle would greatly help with finding the cause of your error.

Ad
source: stackoverflow.com
Ad