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.
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)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With