Search code examples
jqueryknockout.jssingle-page-applicationdynamic-html

Knockout goes crazy when I applyBindings twice with dynamic html


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

Solution

  • 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/