Rebind knockout js when I need to redraw html with bindings
found solution here:
How to clear/remove observable bindings in Knockout.js?
var element = $('#elementId')[0];
ko.cleanNode(element);
and then
ko.applyBindings(myVieModel, parentDiv)
Alan Budzinski
Updated on June 21, 2022Comments
-
Alan Budzinski almost 2 years
I have a situation where I build a div container dynamically that has other html elements inside bonded to my knockout view model. It works up to the point where I call a method on my knockout view model that needs to redraw the whole div. After the redraw knockout stops working.
for example:
calendar += ('<div class="month-nav-container"><div class="nav-prev" data-bind="click: $root.showPreviousMonthOnPrevMonthBtnClick" ><<<</div><span class="month-name-calendar">' + monthNames[month] + '</span><div class="nav-next" data-bind="click: $root.showNextMonthOnNextMonthBtnClick" >>>></div></div>');
I build my calendar control like so of course this is just part of it, but I hope you get the general Idea.
my knockout view model method:
self.showPreviousMonthOnPrevMonthBtnClick = function () { alert("prev"); var $calendar = $("#calendar"); $calendar.empty(); ////// previous month if (self.calendarDisplayDate.month == 0) { $calendar.calendarWidget({ month: 12, year: self.calendarDisplayDate.year - 1 }); } else { $calendar.calendarWidget({ month: self.calendarDisplayDate.month - 1, year: self.calendarDisplayDate.year}); } }
On my page load I build my calendar div, then I call ko.applyBindings() to my view model and it works. But when I click on the btn that calles my previous month method which needs to redraw calendar according to the right month, knockout stops working. I redraw the whole parent div that holds all the knockout bindings. Does anyone know solution to my problem. I need to redraw the div that has KO bindings inside so maybe what i'm looking for is some kind of bindings refresh method of Knockout ?