Wait for ajax result to bind knockout model

I have a function getGeneralthat calls ajax get. When ajax receives the data (json), it creates a KO model from the given json and returns the created KO.

When a knockout model is created and values ​​are assigned, a knockout is called applybindings. Here is my code:

Defines GeneralModelsome related functions (inside " GeneralModel.js"):

var GeneralModel = function() {

   //for now it is empty as data ar binded automatically from json
   // CountryName is one of the properties that is returned with json
} 

function getGeneral(pid) {
    $.ajax({
        url: "/api/general",
        contentType: "text/json",
        dataType: "json",
        type: "GET",
        data: { id: pid},
        success: function (item) {
            var p = new GeneralModel();
            p = ko.mapping.fromJS(item);
            return p;
        },
        error: function (data) {

        }
    });    
}

This is called from another file (GeneralTabl.html), it must call the get function applybindingsto update the interface:

var PortfolioGeneral = getGeneral("@Model.Id");
ko.applyBindings(PortfolioGeneral, document.getElementById("pv-portfolio-general-tab"));

However, in this case I get an error (CountryName not defined). This is because it applybindingshappens before ajax returns the data, so I do applyBindings for an empty model with undefined properties.

Json to Model :    p = ko.mapping.fromJS(item);

GeneralModel , ( ):

  var GeneralModel = function() {    
      CountryName = ko.observable();
      ...
  } 

"CountryName ".

?

1) - getGeneral GeneralModel, GeneralModel?

2) , - " ajax" applybindings?

, , KO JS.

. , , Ajax - Async, , , , getGeneral .

0
1

:

function getGeneral(pid) {
    return $.ajax({
        url: "/api/general",
        contentType: "text/json",
        dataType: "json",
        type: "GET",
        data: {
            id: pid
        }
    });
}

getGeneral("@Model.Id").done(function (item) {
    var p = new GeneralModel();
    p = ko.mapping.fromJS(item);
    ko.applyBindings(p, document.getElementById("pv-portfolio-general-tab"));
}).fail(function () {
    //handle error here
});
+3

Source: https://habr.com/ru/post/1014396/


All Articles