我正在引导模态中创建一个淘汰赛模型。最初,模型是正确创建并绑定到模板的,但是当关闭并重新打开模态时,我最终会在模板中找到多个项目。该模型似乎没有通过多个modal.show()调用重新实例化。我以同样的问题将我的真实示例分解为以下示例。
由于我的真实世界代码,我调用ko.cleanNode()来清除绑定,因为没有它,我会得到“您不能多次将绑定应用于同一元素”。错误。但这似乎无法清除节点。我在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');
});
我希望重置模型,并在结果中显示正确的项目数。
答案 0 :(得分:0)
我认为您应该在关闭模式对话框之后保留绑定,只更改“人”的内容。
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');
});