无法读取对象的子对象

时间:2019-03-08 20:30:05

标签: javascript knockout.js

我不确定如何读取属性,我定义了此javascript函数

function Criteria(object1, object2, object3, object4) {
    var self = this;
    self.object1 = ko.observable(object1);
    self.object2 = ko.observable(object2);
    self.object3 = ko.observable(object3);
    self.object4 = ko.observable(object4);
}

然后我将主视图模型定义如下

   var vmBudget = function () {
        var self = this;
        this.criterias = ko.observableArray();
        this.initialize = function () {
          self.criterias.push(new Criteria("test","","",""));
          self.criterias.push(new Criteria("", "test2", "", ""));
        };
        alert(JSON.stringify(self.criterias()[0].object1()));
   }

在我的html上

<script>
    $(document).ready(function () {
        var vm = new vmBudget();
        ko.applyBindings(vm, document.getElementById("L09budget"));
        vm.initialize();
    });
</script>

一旦我有了variablie Initialie,那么json是{},我就期望像这样的Json

{
Object1: ""
Object2: ""
Object3: ""
Object4: ""
}

1 个答案:

答案 0 :(得分:1)

您的警报会在您的初始化将任何内容推入criterias数组之前触发,因此,criterias()[0]是当时未定义的。

如果将警报移到初始化函数中,以便在将项目推入数组后发生,您应该会看到预期的数据。

function Criteria(object1, object2, object3, object4) {
   var self = this;
   self.object1 = ko.observable(object1);
   self.object2 = ko.observable(object2);
   self.object3 = ko.observable(object3);
   self.object4 = ko.observable(object4);
}

var vmBudget = function() {
   var self = this;
   this.criterias = ko.observableArray();
   this.initialize = function() {
      self.criterias.push(new Criteria("test", "", "", ""));
      self.criterias.push(new Criteria("", "test2", "", ""));
      alert(JSON.stringify(self.criterias()[0].object1()));
   };
}

var vm = new vmBudget();
ko.applyBindings(vm);
vm.initialize();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>