如何使用knockout js从子数组访问父变量

时间:2012-06-12 11:37:30

标签: knockout.js knockout-2.0

我正在使用淘汰赛,并有一个数组“属性”,每个“属性”可以有子“属性”

一切都很好,除了应该继承数组“TabID”的属性 - 例如,如果在父“Property”上更改它,它也应该更改子“Property”

我试图通过使用创建计算器来实现这一点,例如。

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

然后意识到$ parent只能在foreach循环中使用

我也试过将父母传递给构造函数,例如

var childproperty = function(parent,[other properties]){
this.TabID = ko.computed(function(){
return parent.TabID(); // OR return parent.TabID;
}
有人能指出我正确的方向吗?作为旁注,我还需要能够访问父项以获得基于零的[i] caclulation

即每个父属性应该是properties [i] .propitem,其中i =基于每个父级+他们的子属性的计算值

例如:如果父属性1有3个子属性,则父属性1应为i = 0,childproperties(i = 1,2,3),然后父属性2的“i”为4

我知道......我没有多少要求,我不期待一个完美的解决方案,但是如果有人能够指出我正确的方向,我将非常感激。

干杯。

1 个答案:

答案 0 :(得分:2)

我已经设法通过使用以下功能来实现这一目标,希望这可以帮助其他人遇到同样的问题

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

我也注意到,因为我的父母正在调用函数中添加孩子,所以我不能使用"这个"

我的父母资产现在是

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

这很有效 - 如果更改了父tabid,则该值将由子属性反映。我只需要使用$ parentContext访问的foreach循环中的父索引。$ index()