I am trying to write a program which automatically converts two units between each other and fills the other unit with the converted value i.e. a monthly salary to hourly salary converter.
To better demonstrate what I'm trying to do, here is a stripped version of my knockout model:
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);
});
}
}
However, this results in a call stack exceeded exception (hourlyRate updates monthlyRate, which then updates hourlyRate, which in turn updates monthlyRate... indefinitely).
How do I prevent this from happening?