Set value of observable in asynchronous function

邮差的信 提交于 2019-12-08 05:13:16

问题


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?


回答1:


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);
        }
    });
}


来源:https://stackoverflow.com/questions/42645296/set-value-of-observable-in-asynchronous-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!