Knockout - 如何同时设置子级和父级的计算属性?
我有一个项目集合,我想显示每个项目的总数以及单独的百分比。问题似乎是我在计算总数时需要父对象的引用。所以我想我将为 Collection 定义一个计算的 getTotal 并为该项目定义一个百分比。
function Collection() {
var self = this;
self.parts = ko.observableArray();
self.getTotal = ko.computed(function() {
var total = self.parts.length;
return total;
});
}
function Part(amount, parent) {
var self = this;
self.amount = ko.observable(amount);
self.parent = parent;
self.percentage = ko.computed(function() {
return self.amount() / self.parent.getTotal();
});
}
var partsData = [40, 50, 30];
var collection = new Collection();
for (var i = 0; i < partsData.length; ++i) {
collection.parts.push(new Part(partsData[i], collection));
}
ko.applyBindings(collection);
我的 HTML 是
<ul data-bind="foreach: parts">
<li>
<p data-bind="text: amount"></p>
<p data-bind="text: percentage"></p>
</li>
</ul>
但是 Collection.parts 始终是空的。由于某种原因推动它不会触发重新计算的项目。
这也是这样做的正确方法吗?我现在可以弄清楚如何同时在 Collection 中创建一个 observableArray,同时为每个子项提供对父对象的引用。
I have a Collection of items that I would like to display the Total as well as individual Percentage of each item. The problem seems to be that I need a reference of parent object when computing the total. So I figured I'll define a computed getTotal for the Collection and a percentage for the item.
function Collection() {
var self = this;
self.parts = ko.observableArray();
self.getTotal = ko.computed(function() {
var total = self.parts.length;
return total;
});
}
function Part(amount, parent) {
var self = this;
self.amount = ko.observable(amount);
self.parent = parent;
self.percentage = ko.computed(function() {
return self.amount() / self.parent.getTotal();
});
}
var partsData = [40, 50, 30];
var collection = new Collection();
for (var i = 0; i < partsData.length; ++i) {
collection.parts.push(new Part(partsData[i], collection));
}
ko.applyBindings(collection);
And my HTML is
<ul data-bind="foreach: parts">
<li>
<p data-bind="text: amount"></p>
<p data-bind="text: percentage"></p>
</li>
</ul>
However the Collection.parts is always empty. For some reason push it not triggering the items to be recalculated.
Also is this the right way for doing this? I could now figure out how I could simultaneously create an observableArray in the Collection while giving each child item a reference to the parent object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(我在这里使用 jQuery.map)
网页:
(I use jQuery.map here)
Html: