Force template re-rendering knockout
http://stackoverflow.com/questions/7516636/knockout-js-templates-foreach-force-complete-re-render
HTML
<script src="http://rniemeyer.github.com/KnockMeOut/Scripts/knockout-1.3pre.js"></script>
<ul data-bind="alwaysRerenderForEach: { name: 'itemTmpl', foreach: items }"></ul>
<button data-bind="click: churn">Churn Last</button>
<script id="itemTmpl" type="text/html">
<li>
<span data-bind="text: name"></span>
<span data-bind="text: timestamp()"></span>
</li>
</script>
JavaScript
ko.bindingHandlers.alwaysRerenderForEach = {
init: function(element, valueAccessor) {
return ko.bindingHandlers.template.init(element, valueAccessor);
},
update: function(element, valueAccessor, allBindings, viewModel, context) {
valueAccessor().foreach();
ko.utils.domData.clear(element);
$(element).empty();
return ko.renderTemplateForEach(valueAccessor().name, valueAccessor().foreach, {}, element, context);
}
};
function Item(name) {
this.name = ko.observable(name);
this.timestamp = function() {
return new Date().getTime();
}
}
var viewModel = {
items: ko.observableArray([new Item("one"), new Item("two"), new Item("three")]),
churn: function() {
var item = new Item("three");
this.items.pop();
this.items.push(item);
}
};
ko.applyBindings(viewModel);