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">×</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.
I think you should keep the binding after closing the modal dialog, changing only the content of "persons".