gpt4 book ai didi

jquery - 当我使用动态 html 两次应用绑定(bind)时, knockout 变得疯狂

转载 作者:行者123 更新时间:2023-12-01 01:01:51 25 4
gpt4 key购买 nike

我正在创建一个带有 knockout 的单页应用程序...

我有一个 GlobalViewModel 来管理所有动态页面(我通过 ajax 获取 html)。

这是我的问题的示例:

http://jsfiddle.net/zWtrr/7/

当我加载同一模板两次(在“显示模板”中单击两次)时, knockout 会变得疯狂并重复数据......如果您检查可观察数组,则没有重复数据。

HTML:

<div id="container">
<button data-bind="click: showView">show template</button>
<div data-bind="html: templateHtml"></div>
</div>

脚本:

function GlobalViewModel(){
var self = this;
self.templateHtml = ko.observable();
self.templateVM = ko.observable();

self.showView = function(){
//i get this html from ajax
var pageHtml = "<div id='template' data-bind='with: templateVM'>"+
"<button data-bind='click: showAll'>All</button>" +
"<button data-bind='click: showNames'>Names</button>" +
"<button data-bind='click: showLastNames'>LastNames</button>" +
"<button data-bind='click: showNickNames'>NickNames</button>" +
"<ul data-bind='foreach: resultsToShow'>" +
" <li data-bind='text: $data'></li>" +
"</ul>" +
"</div>";
self.templateHtml(pageHtml)
self.templateVM(new ViewModel())
ko.cleanNode(document.getElementById("template"))
ko.applyBindings(window.gvm, document.getElementById("template"));
}

}
function ViewModel(){
var self = this;
self.selected = ko.observable("All");
self.resultsToShow = ko.observableArray([]);
self.result1 = ["Facu", "Feli", "Juli"];
self.result2 = ["Perez","Gonzales","Garcia"];
self.result3 = ["Piti", "Tito", "Gato"];

self.showAll = function (){
self.resultsToShow(self.result1.concat(self.result2,self.result3));
self.selected("All");
}

self.showNames = function (){
self.resultsToShow(self.result1);
self.selected("Names");
}

self.showLastNames = function (){
self.resultsToShow(self.result2);
self.selected("LastNames");
}

self.showNickNames = function (){
self.resultsToShow(self.result3);
self.selected("NickNames");
}
self.showAll();
}
window.gvm = new GlobalViewModel();
ko.applyBindings(window.gvm, document.getElementById("container"));

最佳答案

清洁原来的“容器”似乎有效。

    self.showView = function(){
...
...
ko.cleanNode(document.getElementById("container"));
ko.applyBindings(window.gvm, document.getElementById("container"));
.....
}

http://jsfiddle.net/zWtrr/8/

关于jquery - 当我使用动态 html 两次应用绑定(bind)时, knockout 变得疯狂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15365202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com