小编Fac*_*ini的帖子

当我使用动态html两次applyBindings时,Knockout会变得疯狂

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

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

这是我的问题的一个例子:

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

当我加载相同模板2次(在"显示模板"中单击2次)时,敲门声变得疯狂并重复数据......如果检查可观察数组,则没有重复数据.

HTML:

<div id="container">
    <button data-bind="click: showView">show template</button>
    <div data-bind="html: templateHtml"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

脚本:

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"));
    } …
Run Code Online (Sandbox Code Playgroud)

jquery dynamic-html knockout.js single-page-application

3
推荐指数
1
解决办法
5229
查看次数