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

标签 knockout.js knockout-2.0

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

一切都很好,除了数组“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

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

干杯。

最佳答案

我已经通过使用以下方法成功地解决了这个问题,希望这能帮助遇到同样问题的其他人

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

我还注意到,因为我的 parent 正在调用从函数中添加 child ,所以我不能只使用“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 发生更改,该值将由子属性反射(reflect)。我只需要在 foreach 循环中使用 $parentContext.$index() 访问的父索引

关于knockout.js - 如何使用knockout js从子数组访问父变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10995852/

相关文章:

knockout.js - knockout : partial mapping of arrays

javascript - DevExtreme 使用 knockout 加载 JSON 作为数据源

javascript - Knockout.js Select2 绑定(bind)。 Select2 升级到 v4 后出现故障

javascript - 如何使用 KnockoutJS 在 foreach 循环中指定不同的点击绑定(bind)

javascript - knockout : How to run script after inserting data in observable array

javascript - knockout 延长器或绑定(bind)?

knockout.js - 如何防止依赖可观察量的递归

javascript - 最新的 knockout 和 jquery ui 对话框错误 : cannot call prior to initialization

javascript - knockout.js 在数据绑定(bind)声明中分配 observable

javascript - foreach 完成渲染时的自定义绑定(bind)