javascript 当我需要使用绑定重新绘制 html 时重新绑定淘汰赛
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18859307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rebind knockout js when I need to redraw html with bindings
提问by Alan Budzinski
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.
我有一种情况,我动态地构建了一个 div 容器,里面有其他 html 元素绑定到我的淘汰赛视图模型。它一直工作到我在我的淘汰赛视图模型上调用一个需要重绘整个 div 的方法。重绘淘汰赛停止工作后。
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 ?
在我的页面加载时,我构建了我的日历 div,然后我将 ko.applyBindings() 调用到我的视图模型并且它可以工作。但是当我点击调用我的上个月方法的 btn 需要根据正确的月份重绘日历时,淘汰赛停止工作。我重绘了包含所有淘汰绑定的整个父 div。有谁知道我的问题的解决方案。我需要重绘里面有 KO 绑定的 div,所以也许我正在寻找的是某种 Knockout 的绑定刷新方法?
回答by Alan Budzinski
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)
回答by Nikos
Make sure your all your html elements that need updated bind to the observable functions ie observablefoo and not observablefoo()
确保所有需要更新的 html 元素都绑定到 observable 函数,即 observablefoo 而不是 observablefoo()