使用knockout计算函数更新文本

时间:2017-09-15 10:05:09

标签: mvvm knockout.js

在表格中,我有一个复选框绑定到可观察数组中的bool。

如果选中/取消选中表格中的任何复选框,我想更新一些带有检查总数的文本。

我无法触发计算函数,我尝试在数组和location.isSelected中使用ko.utils.unwrapObservable在下面的'if'语句中,我只是在错误的地方使用它吗?

<input type="checkbox" data-bind="checked: isSelected"/>

<span class="text-left h5 ">Total Selected:</span><span data-bind="text: totalSelected" /> 


self.totalSelected = ko.computed(function () {
    var selected = 0;
    ko.utils.arrayForEach(self.SelectedLocations(), function (location) {
        if (location.isSelected == true) {
            selected = (+selected) + 1;
        }
    });
    return selected;
}, self).extend({ notify: 'always' });

1 个答案:

答案 0 :(得分:0)

其中一个问题是isSelected被视为计算中的变量:location.isSelected == true。但是,如果您打算将复选框绑定到它,则它必须是可观察的。

所以,我已经宣布了一个函数来创建self.SelectedLocations的子项为:

var locationObservable = function() {
  var self = this;
  self.isSelected = ko.observable(false);
};

然后,您可以按如下方式更改计算变量中的计数:

if (loc.isSelected()) {
    selected++;
  }

var locationObservable = function(selected) {
  var self = this;
  self.isSelected = ko.observable(selected);
};

var model = function() {
  var self = this;

  self.SelectedLocations = ko.observableArray();
  self.SelectedLocations.push(new locationObservable(false)); // Set the state of the checkbox here.
  self.SelectedLocations.push(new locationObservable(true));
  self.SelectedLocations.push(new locationObservable(false));

  self.totalSelected = ko.computed(function() {
    var selected = 0;
    ko.utils.arrayForEach(self.SelectedLocations(), function(loc) {
      if (loc.isSelected()) {
        selected++;
      }
    });
    return selected;
  }, self);
};

var vm = new model();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div data-bind="foreach: SelectedLocations">
  <input type="checkbox" data-bind="checked: isSelected" />
</div>


<span class="text-left h5 ">Total Selected:</span><span data-bind="text: totalSelected" />