Knockout model bindings not clearing when new mode

2019-08-27 15:18发布

I am creating a Knockout model within a bootstrap modal. Initially the model is created and bound to the template correctly, however when closing and reopening the modal I end up with multiple items in the template. The model doesn't seem to be re-instantiated with multiple modal.show() calls. I have broken down my real world example to that below with the same issues.

Because of my real world code I call ko.cleanNode() to clear the bindings as without it I get the 'You cannot apply bindings multiple times to the same element.' error. But this does not seem to clean the nodes. I have an example on 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');
});

I am expecting the model to be reset and the correct number of items showing in the result.

标签: knockout.js
1条回答
我只想做你的唯一
2楼-- · 2019-08-27 15:46

I think you should keep the binding after closing the modal dialog, changing only the content of "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');
});
查看更多
登录 后发表回答