Knockout mapping data from ajax post vs Static data

164 Views Asked by At

I've encounted a strange problem with Ko mapping. I use this piece of code:

var PList = [{ "Region": { "RegionName": "SomeRegion" }, "CDetails": {}, "Category": { "Name": "SomeCategory" }, "PSource": 1, "PDate": "0001-01-01T00:00:00"}];

var PViewModel = ko.mapping.fromJS(search('someSearch', 'True'));
var PViewModel2 = ko.mapping.fromJS(PostList);

function search(queryString, isFirst) {
    $.ajax({
        type: 'POST',
        url: 'url',
        data: { 'searchQuery': queryString },
        dataType: 'json',
        success: function (dt) {
            if (isFirst != 'True') {
                ko.mapping.fromJS(dt, PostsViewModel);
            }
            return dt;
        }
    });
};

Strangely I see 2 outcomes:

  1. When I go to PViewModel (the one populated by ajax) I see it as undefined
  2. When I go to PViewModel2 (the one with static data) I can see the objects as expected

*The static data of PViewModel2 is just a copy of the data returned by the ajax post.

My questions are:

  1. Does anyone know why is this so? And how to fix it?
  2. Furthermore, is the if (isFirst != 'True') clause the right way to init the ko view model?
1

There are 1 best solutions below

0
On

You are dealing with an asynchronous operation (an Ajax request). These operations do not have return values. Therefore, this can never work:

ko.mapping.fromJS(search('someSearch', 'True'));

That's what the success callback is for. Incoming data can only be handled there.

function search(queryString, targetObservable) {
    $.ajax({
        type: 'POST',
        url: 'url',
        data: { 'searchQuery': queryString },
        dataType: 'json',
        success: function (dt) {
            ko.mapping.fromJS(dt, targetObservable);
        }
    });
};

search('someSearch', PostsViewModel);