KO Collection Rebind Problem
Demonstrate a problem with rebinding a collection via KnockoutJS whereby the DOM elements from the previous bind are not removed. The goal is to clear previously bound elements and rebind the collection. The end result should display the same three elements without error. Note: be sure to open the JS console in your browser.
by Craig Boland
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<div id="hssResult" data-bind="foreach: Data">
<div class="row">
<span data-bind="text: Id"></span>
<span data-bind="text: Name"></span>
</div>
</div>
JavaScript
$(document).ready(function () {
var hss = {
Data: [
{ Id: 1, Name: "Larry" },
{ Id: 2, Name: "Moe" },
{ Id: 3, Name: "Curly" }
]
};
// Capture the container element so we can clear it after the first bind.
var el = $("#hssResult");
// First bind
ko.applyBindings(hss, el[0]);
// Clear the first bindings
ko.cleanNode(el[0]);
//TODO: Remove DOM elements created from first bind
//var firstEl = $("#hssResult").children(".row").first();
var firstEl = $("#hssResult .row").first();
//alert(firstEl);
firstEl.text('yo');
//$("#hssResult").children().remove(firstEl);
//$("#hssResult").empty();
//$("#hssResult").children().(firstEl);
//$("#hssResult").children(".row").append("span").text("bro");
//$("#hssResult").children().add("div").text("bro");
//$("#hssResult").add("div").text("bro");
// Second bind
//ko.applyBindings(hss, el[0]);
});