淘汰计算变量未显示

时间:2017-09-30 00:02:33

标签: knockout.js

我有以下可观察内容,但在更新字段时,我的总数不会更新。

var formdata = ko.observable({
  a: 0,
  b: 0,
  c: 0,
  d: 0
});
var calcs = {
  calulatedValues: function() {
    this.total = ko.pureComputed(function() {
      return formdata().a+formdata().b+formdata().c+formdata().d;
    });
  }
}

$(function() {
  ko.applyBindings(formdata, document.getElementByID("myForm"));
  ko.applyBindings(calcs, document.getElementByID("totals"));
});

<div id="totals">
  <div data-bind="with: calculatedValues">
    <div data-bind="total"></div>
  </div>
</div>

Fiddle to show what's happening

1 个答案:

答案 0 :(得分:2)

with绑定会创建一个新的绑定上下文。因此,您应该将其从function更改为:

var calcs = {
  calulatedValues: {
    total: ko.pureComputed(function() {
      return formdata().a + formdata().b + formdata().c + formdata().d;
    });
  }
}

你没有正确绑定total。将其更改为:

<div id="totals">
  <div data-bind="with: calculatedValues">
    <div data-bind="text: total"></div>
  </div>
</div>

由于document.getElementByID("totals")中存在拼写错误,它仍然无法正常工作。它应该是Id

ko.applyBindings(calcs, document.getElementById("totals"));

这里是fiddle

更新

如果您希望在computedab值发生变化时触发c属性,则应将其设为observable s ,而不是formdata

var formdata = {
  a: ko.observable(0),
  b: ko.observable(1),
  c: ko.observable(0),
  d: ko.observable(0)
};

并将total更改为:

total: ko.pureComputed(function() {
  // added the "Number" parsing, otherwise it concatenates numbers as strings
  return Number(formdata.a()) + Number(formdata.b()) + Number(formdata.c()) + Number(formdata.d());
})

Updated fiddle