简体   繁体   English

JavaScript对象文字嵌套对象状态

[英]JavaScript object literal nested object state

I try to call "ViewModel.healthData.get" twice. 我尝试两次调用“ ViewModel.healthData.get”。 In both cases, the method retrieves the data from the Internet. 在这两种情况下,该方法都从Internet检索数据。 How can I make the "data" field retain its data? 如何使“数据”字段保留其数据?

function MyObject() {
    this.ViewModel.healthData.get(this.ViewModel.healthData.set);
}
MyObject.prototype = {
    ViewModel: {
        healthData: {
            data: null,
            set: function (result) {
                console.log("data from set");
                this.data = ko.mapping.fromJS(result);
            },
            get: function (callback) {
                if (this.data === null) {
                    $.ajax({
                        url: "/api/Health",
                        type: 'GET',
                        async: true,
                    }).done(callback);
                } else {
                    console.log("direct data");
                    return this.data;
                }
            }
        }
    }
};

I think you might want to have a look at Promises for this, it will simplify your workflow a lot. 我认为您可能希望对此有一个了解,这将大大简化您的工作流程。 Since you are waiting for data to be populated, your calls could happen too soon or too late, but with promises that's not the case. 由于您正在等待填充数据,因此您的呼叫可能为时过早或为时太晚,但承诺并非如此。 Simply call resolve when done (or reject when failed) and pass it the data you received. 只需在完成时调用resolve (或在失败时reject ),然后将您收到的数据传递给它即可。 From then on any function called with .then (and any function called that way since starting the request) will be called immediately with the data in the first argument. 从那时起,任何用.then调用的函数(以及自启动请求以来以这种方式调用的任何函数)都将立即与第一个参数中的数据一起调用。

function MyObject() {
    this.ViewModel.healthData = new Promise(function( resolve, reject ){
        $.ajax({
            url: "/api/Health",
            type: 'GET',
            async: true,
        }).done(function(data){ 
             resolve(ko.mapping.fromJS(result))
        }).fail( reject )
    });
}
MyObject.prototype = { ViewModel: { healthData: null } };

When you create a new MyObject here, it will automatically instantiate the required data inside a promise. 在此处创建新的MyObject ,它将自动在promise中实例化所需的数据。 To Access and use the data, simple use: 要访问和使用数据,简单使用:

myInstanceOfMyObject.ViewModel.healthData.then(function(data){
    // Do whatever you want with the passed data here
});

This will resolve some of your asynchronous woes and highly simplify the structure. 这将解决您的一些异步问题,并大大简化结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM