异步功能中可观察的设定值 [英] Set value of observable in asynchronous function

查看:117
本文介绍了异步功能中可观察的设定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用DevExtreme和淘汰赛.我想从服务器获取JSON-Data并将其保存到可观察对象中.

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

当前方法:

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
}

我是这些情况的新手,所以不确定自己的方法.为了进行测试,我调用了通过按钮手动获取JSON-Data的函数,并且获得了所需的数据,但是可观察对象都包含以下内容:

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?

推荐答案

如何使用

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

这篇关于异步功能中可观察的设定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆