riceTale
riceTale

Reputation: 94

Knockoutjs get parent object

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.

Upvotes: 5

Views: 3945

Answers (1)

Martin
Martin

Reputation: 3286

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

Upvotes: 4

Related Questions