无法访问淘汰可观察数组项

Unable to access knockout observable array item

本文关键字:观察 数组 淘汰 访问      更新时间:2023-09-26

我从web api获取数据并将数据推送到可观察数组中。我想让可观察数组项成为可观察的。然而,如果我把它设为可观察对象,似乎我就不能访问它了。

function KnockoutViewModel() {
  var self = this;
  
  self.ProfileList = ko.observableArray([]);
  
  self.GetProfile = function() {
    $.ajax({
      type: 'GET',
      success: function() {
        $.each(data.ProfileList, function (index, value) {
           self.ProfileList.push(value);
           alert(self.ProfileList()[index].Name) // success
        }
      }
    });
  }
      
  self.GetProfile();
}
           
function KnockoutViewModel() {
  var self = this;
  
  self.ProfileList = ko.observableArray([]);
  
  self.GetProfile = function() {
    $.ajax({
      type: 'GET',
      success: function() {
        $.each(data.ProfileList, function (index, value) {
           self.ProfileList.push(ko.observable(value));
           alert(self.ProfileList()[index].Name) // fail. Object does not support property or method 'Name'
        }
      }
    });
  }
      
  self.GetProfile();
}

你直接推动object(通过使其可观察)到observableArray听起来对吗?不(我相信你可能想让Name成为可观察的)。但是你可以通过这样做得到输出self.ProfileList()[index]().Name check 这里

首选方式:

viewModel:

 function convert(data) {
    this.Name = ko.observable(data.Name)
    this.place = ko.observable(data.place)
    this.age = ko.observable(data.age)
}
function KnockoutViewModel() {
    var self = this;
    self.ProfileList = ko.observableArray([]);
    self.GetProfile = function () {
        var data = [{
            'Name': 'Super',
                'place': 'Ind',
                'age': 25
        }, {
            'Name': 'Cool',
                'place': 'Aus',
                'age': 15
        }]
        //Manual way with function defined 
        //self.ProfileList(ko.utils.arrayMap(data, function (value) {
        //  return new convert(value)
        //}))
        //Using Mapping Plugin
        ko.mapping.fromJS(data,{},self.ProfileList)
    }
    self.GetProfile();
}
ko.applyBindings(new KnockoutViewModel());

工作样本此处

尝试使用映射模块:

self.ProfileList.push(ko.mapping.fromJS(value));