【发布时间】:2019-03-27 22:13:55
【问题描述】:
我正在尝试编写一个程序,该程序自动将两个单位相互转换,并用转换后的值填充另一个单位,即月薪到小时薪的转换器。
为了更好地展示我正在尝试做的事情,这里是我的淘汰模型的精简版:
class Model {
hourlyRate: KnockoutObservable<number>;
monthlyRate: KnockoutObservable<number>;
hoursPerWeek: KnockoutObservable<number>;
constructor() {
this.hourlyRate = ko.observable<number>();
this.monthlyRate = ko.observable<number>();
this.hoursPerWeek = ko.observable<number>(40);
this.monthlyRate.subscribe((newValue: number) => {
const hourlyRate = newValue * 3 / 13 / this.hoursPerWeek();
this.hourlyRate(hourlyRate);
});
this.hourlyRate.subscribe((newValue: number) => {
const monthlyRate = newValue * this.hoursPerWeek() * 13 / 3;
this.monthlyRate(monthlyRate);
});
}
}
但是,这会导致调用堆栈超出异常(hourlyRate 更新monthlyRate,然后更新hourlyRate,然后更新monthlyRate...无限期地更新)。
如何防止这种情况发生?
【问题讨论】:
-
检查这个thread 我怀疑你需要重构一些东西才能让它正常工作。
标签: javascript typescript knockout.js