knockout JS无法访问observableArray的元素

knockout JS unable to access the elements of observableArray

我已经创建了 knockout observable 数组并添加了如下元素,

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"}

不知道在做什么wrong/missing,我可以知道如何访问 observableArray 元素吗?

更改 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 以获得直观的解释。