Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockoutjs get parent object

Tags:

knockout.js

I am having difficulties on getting the parent object's certain field from child object using knockout.js.

function Child(info){
    var self = this;
    self.x = info.x;
    self.y = info.y;
    self.parentThing = parent.fieldToGet();  // This is when I had problem
}

function Main() {
    var self = this;
    self.fieldToGet = ko.observable();
            self.things = ko.observableArray();
    self.postFunction = function(){
        $.post('XXX.php', $("form#filterForm").serialize(), function(data){
                var mappedThing = $.map(data.data, function(info){return new Child(info); });
                self.things(mappedThing);
            }
        }, 'json');
    };
}
var main = new Main();
ko.applyBindings(main, $("div#main")[0]);



The hierachy is Main has several Child. In Child object I want to get its parents 'attribute': fieldToGet.

like image 257
riceTale Avatar asked Oct 03 '22 06:10

riceTale


1 Answers

I think a good solution will be to pass the parent class to the child as parameter.

function Child(info, parent){
    var self = this;
    self.parent = parent;
    self.x = info.x;
    self.y = info.y;
    self.parentThing = parent.fieldToGet();  // This is when I had problem
}


function Main() {
    var self = this;
    self.fieldToGet = ko.observable();
    self.things = ko.observableArray();
    self.postFunction = function()
    {
        $.post('XXX.php', $("form#filterForm").serialize(), function(data) {
              var mappedThing = $.map(data.data, function(info) { 
                 return new Child(info, self);        
              });
              self.things(mappedThing);
        }, 'json');
    };
}
  var main = new Main();
  ko.applyBindings(main, $("div#main")[0]);

As you can see in my example the parent instance (self) will be passed as parameter to the child class in the constructor (function Child(info, parent))

like image 150
Martin Avatar answered Oct 07 '22 18:10

Martin