Jseb
Jseb

Reputation: 1934

Can't read child of object

I am unsure how to read the the properties, I have this javascript function defined

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);
}

Then I define my main view modle as follow

   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()));
   }

On my html

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

Once I have the variablie Initialie the json is {}, I am expecting a Json like

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

Upvotes: 0

Views: 42

Answers (1)

Jason Spake
Jason Spake

Reputation: 4304

Your alert is firing before your initialize pushes anything into the criterias array, so yes criterias()[0] is undefined at that point.

If you move the alert into the initialize function so that it happens after the items get pushed into the array you should see your expected data.

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>

Upvotes: 1

Related Questions