Rebind knockout js when I need to redraw html with bindings

I have a situation where I dynamically create a div container that has other html elements related to my knockout model. It works to such an extent that I call the method on my model with a knockout that should redraw the entire div. After the knockout is redrawn, it stops working.

eg:

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 create my calendar this way, of course, this is only part of it, but I hope you get a general idea.

my knockout 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 create my calendar div, then I call ko.applyBindings () on my view model, and it works. But when I click on btn, which calls my method of the previous month, which needs to be redrawn the calendar according to the correct month, the knockout stops working. I redraw the entire parent div that contains all the knockout bindings. Does anyone know a solution to my problem. I need to redraw a div that has KO bindings inside, so maybe what I'm looking for is some kind of method for updating Knockout bindings?

+4
source share
2 answers

found a solution here:

How to clear / remove observable bindings in Knockout.js?

  var element = $('#elementId')[0]; ko.cleanNode(element); 

and then

  ko.applyBindings(myVieModel, parentDiv) 
+18
source

Make sure that all your html elements that need updating are attached to observable functions, i.e. observablefoo and not observablefoo ()

0
source

Source: https://habr.com/ru/post/1502680/


All Articles