2

I am using knockout and have an array "Properties" and each "Property" can have child "properties"

all is fine except that there is a property of the array "TabID" that should be inherited - for example if it is changed on the parent "Property" it should also change on the child "Property"

I've tried to get this to work by using creating a computed, eg.

this.TabID = ko.computed(function(){
return $parent.TabID();
});

and then realised that $parent was only available within the foreach loop

I've also tried passing the parent through to in the constructor eg

var childproperty = function(parent,[other properties]){
this.TabID = ko.computed(function(){
return parent.TabID(); // OR return parent.TabID;
}

could somebody point me in the right direction please? As a side note I also need to be able access the parent for a zero based [i] caclulation

that is each parent property should be properties[i].propitem where i = a computed value based on each parent + their child properties

for example: if parent property 1 has 3 child properties, then parent property 1 should be i=0, childproperties (i=1,2,3) and then parent property 2 would have an "i" of 4

I know... I don't ask for much right, I'm not expecting a perfect solution for my issues but if somebody can at least point me in the right direction I would be very grateful.

Cheers.

1 Answer 1

2

I've managed to get this working by using the following, hopefully this will help anybody else experiencing the same issue

var childproperty = function(parent,[other properties]){
this.parent = ko.observable(parent);
this.TabID = ko.computed(function(){
return this.parent().TabID(); // OR return parent.TabID;
}

I also noticed that because my parent was calling adding the child from within a function i couldn't just use "this"

my parent property is now

var parentproperty = function([properties]){
var p = this;
p.childproperties = ko.observableArray();
p.TabId = ko.observable(1);
p.addChild = function(){
p.childproperties.push(new childproperty(p,[other properties]));
}

this works perfectly - if the parent tabid is changed, the value is reflected by the child property. I only really needed the parent index inside the foreach loop which I accessed with $parentContext.$index()

Sign up to request clarification or add additional context in comments.

2 Comments

Could you not have just passed the parent like so: <div foreach="items"><child data-bind="click: Foo($parent)"
@Nikos - no, because if you do that, Foo($parent) will be executed at the time of binding, you need to set click to a "delegate".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.