【问题标题】:How can I access a parent variable from a child array using knockout js如何使用淘汰赛js从子数组访问父变量
【发布时间】:2012-06-21 14:57:19
【问题描述】:

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

除了数组“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] 计算

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

例如:如果父属性 1 有 3 个子属性,那么父属性 1 应该是 i=0,子属性 (i=1,2,3),然后父属性 2 的“i”应该是 4

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

干杯。

【问题讨论】:

    标签: knockout.js knockout-2.0


    【解决方案1】:

    我已经设法通过使用以下方法来解决这个问题,希望这可以帮助遇到同样问题的其他人

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

    我还注意到,因为我的父母正在调用从函数中添加孩子,所以我不能只使用“this”

    我的父属性现在是

    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.$index() 访问的 foreach 循环中的父索引

    【讨论】:

    • 你能不能像这样传递父级:
    • @Nikos - 不,因为如果这样做,Foo($parent) 将在绑定时执行,您需要将 click 设置为“委托”。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签