0

多次单击按钮会在 UI 中复制数据。

我对每次点击的期望:* Name1 * Name2

但:* Name1 * Name1 * Name2 * Name2

<html>
<head>
  <script src="http://knockoutjs.com/downloads/knockout-3.3.0.js" type="text/javascript"></script>
</head>
<body>
  <div id="myDiv">
    <div data-bind="foreach: Data">
      * <span data-bind="text: Name"></span>
    </div>
  </div>
  <button onclick="f1()">Click Me!</button>
  <script type="text/javascript">
    function myViewModel(data){
      var self = this;
      self.Data = data;
    }    
    function f1() {
      var d = [{ "Name": "Name1" }, { "Name": "Name2" }];
      ko.cleanNode(document.getElementById('myDiv'));
      ko.applyBindings(new myViewModel(d), document.getElementById('myDiv'));
      return false;
    }
  </script>
</body>
</html>

4

1 回答 1

0

您应该只调用 ko.applyBindings 一次,清理和重新应用不是最佳做法。试试这样的事情:

<html>
<head>
  <script src="http://knockoutjs.com/downloads/knockout-3.3.0.js" type="text/javascript"></script>
</head>
<body>
  <div id="myDiv">
    <div data-bind="foreach: Data">
      * <span data-bind="text: Name"></span>
    </div>
  </div>
  <button data-bind="click: f1">Click Me!</button>
  <script type="text/javascript">
    // viewmodel definition with click handler
    function myViewModel(data){
      var self = this;
      self.Data = ko.observableArray(data);
      self.f1 = function() {
          self.Data([{ "Name": "Name1" }, { "Name": "Name2" }]);
      }
    }    

    // create instance of viewmodel on document ready, apply bindings
    $(function(){
      var vm = new myViewModel();
      ko.applyBindings(vm, document.getElementById('myDiv'));
    });

  </script>
</body>
</html>
于 2015-05-26T14:38:39.420 回答