Marcel
Marcel

Reputation: 927

Set value of observable in asynchronous function

I'm using DevExtreme and knockout. I want to fetch JSON-Data from a server and save it into an observable.

Current approach:

var dataArray = ko.observableArray();
var dataId = ko.observable("");

MyApp.overview = function (params) {
    "use strict"; 

    var viewModel = {
        [...]
    }

    return viewModel;
};

function getDataFromJson() {
    $.ajax({
        url: 'http://localhost:56253/test/3?format=json',
        dataType: 'json',
        success: function (data) {
            var entries = $.map(data, function (item) { return new entry(item) });
            // first entry is ID
            for (var i = 1; i < entries.length; i++) {
                dataArray.push(entries[i]);
            }
        }
    });
}

function getIDFromJson() {
    $.ajax({
        url: 'http://localhost:56253/test/3?format=json',
        dataType: 'json',
        success: function (data) {
            dataId(data.ID);
        }
    });
}

function entry(data) {
    this.A = data.A,
    this.B = data.B,
    this.C = data.C
}

I'm new to these scenarios, so I'm not sure if my apporach. For testing, I'm calling the functions to get the JSON-Data manually via buttons, and I get the needed data, but the observables both contain this:

function c(){if(0<arguments.length)return c.tb(c[E],arguments[0])&&(c.ga(),c[E]=arguments[0],c.fa()),this;a.l.oc(c);return c[E]}

What am I missing? Or is this approach bad practice in general?

Upvotes: 1

Views: 123

Answers (1)

AMouat
AMouat

Reputation: 755

How I do it is by using the Knockout Mapping Plugin and the fromJSON command (you might need to use fromJS depending on your data format) this maps the data as it comes from the source.

function getDataFromJson() {
    $.ajax({
        url: 'http://localhost:56253/test/3?format=json',
        dataType: 'json',
        success: function (data) {
            ko.mapping.fromJSON(data, {}, self.dataArray);
        }
    });
}

Upvotes: 1

Related Questions