[英]Access a parent's member
Given the following code: 给出以下代码:
self.pcsList = ko.observableArray(ko.utils.arrayMap(pcs, function (pc) {
return {
obCurHp: ko.observable(pc.curHp), obMaxHp: ko.observable(pc.hp),
obHpPerc: ko.computed(function(){return Math.round(this.obCurHp() / this.obMaxHp())*100 + "%";})
};
}));
obHpPrec does not evaluate to anything because neither this.obCurHp()
& this.obMaxHp()
are a thing nor are obCurHp()
& obMaxHp()
. obHpPrec不会计算任何值,因为
this.obCurHp()
和this.obMaxHp()
都不是东西, obCurHp()
和obMaxHp()
也不是东西。
I need to access these members of the current pcsList object so I can construct the computed object. 我需要访问当前pcsList对象的这些成员,以便可以构造计算对象。 How would I go about doing this?
我将如何去做呢?
You need to keep this
in each context separate. 你需要保持
this
在每个方面分开。 You can have a sub model and just create a new instance for each element. 您可以拥有一个子模型,并为每个元素创建一个新实例。
var mainViewModel = function (){
var self = this;
self.pcsList = ko.observableArray(ko.utils.arrayMap(pcs, function (pc) {
return new pcListItemViewModel(pc);
}));
}
var pcListItemViewModel = function (pc){
var self = this;
self.obCurHp = ko.observable(pc.curHp);
self.obMaxHp = ko.observable(pc.hp);
self.obHpPerc = ko.computed(function(){
return Math.round(self.obCurHp() / self.obMaxHp())*100 + "%";
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.