Knockout goes crazy when I applyBindings twice with dynamic html

纵饮孤独 提交于 2019-12-12 14:07:07

问题


I am creating a single page application with knockout ...

I have a GlobalViewModel to admin all dynamic pages (I get the html via ajax).

Here is an example of my problem:

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

When I load 2 times the same template (click 2 times in "show template") knockouts goes crazy and duplicate data... if you check the observable Array, there's no duplicated data.

HTML:

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

Script:

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"));

回答1:


Cleaning the original 'container' seems to work.

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

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



来源:https://stackoverflow.com/questions/15365202/knockout-goes-crazy-when-i-applybindings-twice-with-dynamic-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!