Daniel Mendez
Daniel Mendez

Reputation: 3

Knockout changes the value of one variable

Im am trying to edit one user in knockout, but this happends, i got the element and i send that in a query to Controler, that return my (object) in JSON i save that object in this variable:

var ViewUsuarios = function () {
     self.dato = ko.observableArray();
      var usuariosUri = '/api/Usuarios/';
      var rolesUri = 'api/Rols/';

function ajaxHelper(uri, method, data) {
    self.error('');
    return $.ajax({
        type: method,
        url: uri,
        dataType: 'json',
        contentType: 'application/json',
        //Strinfy convierte una cadena de tipo javascript a objetos tipo JSON
        data: data ? JSON.stringify(data) : null

    }).fail(function (jqXHR, textStatus, errorThrown) {
        self.error(errorThrown);
    });
}

}

all works fine, but when i do this:

 ajaxHelper(usuariosUri + item.ID, 'GET').done(function (data) {
        //alert(JSON.stringify(data));
        self.upUsuario(data); <- Here i have the user
    });

    ajaxHelper(rolesUri + item.RolId,'GET').done(function (data) {
        self.dato(data); <- Here works i have the correct ROL
        alert(JSON.stringify(self.dato())+"Correcto ");
    });
        alert(JSON.stringify(self.dato())+"Incorrecto"); <- Here don't work at first click is null and second have the after element

i don't know where is the error

Upvotes: 0

Views: 71

Answers (1)

usp
usp

Reputation: 94

That's because:

  • alert(JSON.stringify(self.dato())+"Incorrecto"); is called synchronously.
  • self.dato(data); alert(JSON.stringify(self.dato())+"Correcto "); is called asynchronously.

So the actual execution order is:

  1. ajaxHelper(usuariosUri + item.ID, 'GET')
  2. ajaxHelper(rolesUri + item.RolId,'GET')
  3. alert(JSON.stringify(self.dato())+"Incorrecto");
  4. self.upUsuario(data); or
    self.dato(data); alert(JSON.stringify(self.dato())+"Correcto ");

self.dato will be never initialized until 4, although 3 refers self.dato.
That's why self.dato is empty on the first click.
Maybe on the second click, self.dato contains previous result of ajaxHelper.

Upvotes: 1

Related Questions