4

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

我有一个 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>

脚本:

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

1 回答 1

5

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

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

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

于 2013-03-12T15:45:14.403 回答