创建新模型时,敲除模型绑定不清除

Knockout model bindings not clearing when new model created

我正在 bootstrap 模态中创建一个 Knockout 模型。最初模型被创建并正确绑定到模板,但是当关闭和重新打开模式时,我最终在模板中有多个项目。该模型似乎没有通过多次 modal.show() 调用重新实例化。我已将现实世界中的示例分解为以下具有相同问题的示例。

因为我的真实世界代码,我调用 ko.cleanNode() 来清除绑定,因为没有它我得到 'You cannot apply bindings multiple times to the same element.' 错误。但这似乎并没有清理节点。我在 CodePen 上有一个例子:- https://codepen.io/asteropesystems/pen/LKeyoN

HTML

<div id="openModal" class="btn btn-primary">Open modal</div>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
   <div class="modal-content">
    <div class="modal-header">
     <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
     <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">&times;</span>
     </button>
    </div>
   <div class="modal-body">
    <div data-bind="foreach: persons">
     <div data-bind="text: $data"> </div>
    </div>
   </div>
   <div class="modal-footer">
    <div class="btn btn-secondary" id="cancel">Cancel</div>
   </div>
  </div>
 </div>
</div>

JavaScript

var TestModel = function () {
  var self = this;
  self.persons = ko.observableArray();

  for (var m = 0; m < 5; m++) {
    self.persons.push('TEST ' + m);
  }
  return this;
};

$('#openModal').click(function() {

  var model = new TestModel();

  ko.cleanNode(document.getElementById('exampleModal'));
  ko.applyBindings(model, document.getElementById('exampleModal'));

  $('#exampleModal').modal('show');

});

$('#cancel').click(function () {
  $('#exampleModal').modal('hide');
});

我期待模型被重置并且结果中显示正确的项目数。

我认为你应该在关闭模态对话框后保留绑定,只更改 "persons" 的内容。

var TestModel = function ()  {
  let self = this;
  self.persons = ko.observableArray([]);
};

var model = new TestModel();
ko.applyBindings(model, document.getElementById('exampleModal'));

$('#openModal').click(function() {
  model.persons([]);
  for (var m = 0; m < 5; m++) {
    model.persons.push('TEST ' + m);
  }
  $('#exampleModal').modal('show');
});

$('#cancel').click(function () {
  $('#exampleModal').modal('hide');
});