【问题标题】:Knockout observable subscriptions: maximum call stack exceeded淘汰可观察订阅:超出最大调用堆栈
【发布时间】: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


【解决方案1】:

我认为这是使用writable computed observables 的好地方。

这是一个 sn-p(抱歉,我不精通打字稿):

var viewModel = function(){
  this.hourlyRate = ko.observable();
  this.hoursPerWeek = ko.observable(40);
  this.monthlyRate = ko.pureComputed({
    read: function(){
      return this.hourlyRate() * this.hoursPerWeek() *13/3;
    },
    write: function(newValue){
      const hourlyRate = newValue * 3 / 13 / this.hoursPerWeek();
      this.hourlyRate(hourlyRate);
    },
    owner: this
  });
};

ko.applyBindings(new viewModel());
label {
  display: inline-block;
  width: 140px;
  text-align: right;
}

.block {
  padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div class="block">
    <label>Hourly Rate:</label>
    <input type="number" data-bind="value: hourlyRate">
</div>
<div class="block">
    <label>Monthly Rate:</label>
    <input type="number" data-bind="value: monthlyRate">
</div>

【讨论】:

    猜你喜欢
    • 2011-09-17
    • 1970-01-01
    • 2013-04-24
    • 2018-07-28
    • 2015-08-29
    • 2017-06-21
    • 1970-01-01
    • 2014-11-05
    • 2012-09-08
    相关资源
    最近更新 更多