淘汰赛JS无法访问observableArray的元素

时间:2018-09-27 17:40:04

标签: javascript knockout.js oracle-jet

我创建了可剔除的可观察数组并添加了以下元素,

define(['ojs/ojcore', 'knockout', 'jquery', 'ojs/ojtable', 'ojs/ojarraytabledatasource', 'ojs/ojrouter'],
 function(oj, ko, $) {

    function CustomerViewModel() {
      var self = this;
      self.data = ko.observableArray([]);

      var getDataUrl = <rest-api-url>
      var fetchDataPayLoad = JSON.stringify(<json_data>);

      self.fetchData = function(fetchDataPayLoad, fetchDataCallBack) {
             $.ajax({
               url: getDataUrl,
               data: fetchDataPayLoad,
               type: 'POST',
               contentType: 'application/json',
               success: fetchDataCallBack,
               error: function (jqXHR, textStatus, errorThrown) {
                 console.log('Error during fetch');
               }
             });
           };

      function fetchDataCallBack(fetchedData){
             fetchedData.hits.hits.forEach(function(e){
                 var value1 = e._id;
                 value2 = e._value;
                 value3 = e.name;
                 value4 = e.testdata;
                 self.data.push({
                   prop1: value1,
                   prop2: value2,
                   prop3: value3,
                   prop4: value4
                 });
               });
             });
           };
           var fetchDataRun = this.fetchData(fetchDataPayLoad, fetchDataCallBack);
           console.log(self.data());
}
    return new CustomerViewModel();
}
);

当我尝试检查observableArray的长度始终为0时,以及当我在控制台上打印如下所示的相同数据时,

>[]

当我展开时,

>0: {prop1: "value11", prop2: "value12", prop3: "value13", prop4: "value14"}
>1: {prop1: "value21", prop2: "value22", prop3: "value23", prop4: "value24"}

不确定在这里发生了什么错误/遗漏,我可以知道如何访问observableArray元素吗?

1 个答案:

答案 0 :(得分:3)

更改console.log的位置。

function fetchDataCallBack(fetchedData){
    fetchedData.hits.hits.forEach(function(e){
        var value1 = e._id;
        value2 = e._value;
        value3 = e.name;
        value4 = e.testdata;
        self.data.push({
            prop1: value1,
            prop2: value2,
            prop3: value3,
            prop4: value4
        });
    });
    console.log(self.data());
});

您的Ajax调用是异步的,这意味着仅在调用完成后才执行回调函数。当前,您正在使用console.log,而Ajax调用仍在后台运行,因此显示为空。有关直观说明,请参见here