清除 Javascript knockout observableArray 中的所有元素。项目仍然导致重复

clearing all elements from Javascript knockout observableArray. Items remain causing duplicates

我正在尝试创建一个 observableArray 个“Board”对象来填充视图。

我目前可以在每次定时页面刷新后向数组添加新的 Board 对象。但不是清除数组然后从 foreach 循环添加新板,它只是添加到现有的导致重复。

$(document).ready(function() {
    refreshPage();
});

function refreshPage() {
    getGames();
    setTimeout(refreshPage, 10000);
    console.log("Page refreshed");
};

function Board(data) {
    this.gameChannel = ko.observable(data.GameChannel);
    this.HomeTeamImage = ko.observable(data.HomeTeamImage);
    this.HomeTeamName = ko.observable(data.HomeTeamName);
    this.HomeBeerPrice = ko.observable(data.HomeBeerPrice);
    this.HomeTeamArrow = ko.observable(data.HomeTeamArrow);
    this.HomeBeer = ko.observable(data.HomeBeer);
    this.HomeBeerAdjustedPrice = ko.observable(data.HomeBeerAdjustedPrice);
    this.AwayTeamArrow = ko.observable(data.AwayTeamArrow);
    this.AwayBeerPrice = ko.observable(data.AwayBeerPrice);
    this.AwayTeamName = ko.observable(data.AwayTeamName);
    this.AwayBeerAdjustedPrice = ko.observable(data.AwayBeerAdjustedPrice);
    this.AwayBeer = ko.observable(data.AwayBeer);
    this.awayTeamImage = ko.observable(data.AwayTeamImage);
    this.FullScore = ko.computed(function() {
        return data.HomeTeamScore + " | " + data.AwayTeamScore;
    }, this);
}

function vm() {
    var self = this;
    self.gameCollection = ko.observableArray([]);
}

getGames = function() {
    var _vm = new vm();
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/Dashboard/PopulateMonitor/",
        error: errorFunc,
        success: function(data) {
            _vm.gameCollection = [];
            $.each(data, function() {
                _vm.gameCollection.push(new Board(this));
            });
        }
    });

    function errorFunc() {
        alert("Error, could not load gameboards");
    }
    ko.applyBindings(_vm);
}

问题出现在 getGames() 函数中或

行附近
_vm.gameCollection = [];

感谢您提供的任何帮助。不太熟悉 Knockout.js

每次您调用 getGames 您都在创建一个新的“_vm”:

getGames = function () {
    var _vm = new vm();

var _vm = new vm(); 移动到

$(document).ready(function () {
    var _vm = new vm(); // <-- HERE
    refreshPage();
});

有些行也必须移动,请参阅代码段:

$(document).ready(function() {
  _vm = new vm();
  refreshPage();
});


function refreshPage() {

  getGames();
  setTimeout(refreshPage, 10000);
  console.log("Page refreshed");

};


function Board(data) {
  this.gameChannel = ko.observable(data.GameChannel);
  this.HomeTeamImage = ko.observable(data.HomeTeamImage);
  this.HomeTeamName = ko.observable(data.HomeTeamName);
  this.HomeBeerPrice = ko.observable(data.HomeBeerPrice);
  this.HomeTeamArrow = ko.observable(data.HomeTeamArrow);
  this.HomeBeer = ko.observable(data.HomeBeer);
  this.HomeBeerAdjustedPrice = ko.observable(data.HomeBeerAdjustedPrice);
  this.AwayTeamArrow = ko.observable(data.AwayTeamArrow);
  this.AwayBeerPrice = ko.observable(data.AwayBeerPrice);
  this.AwayTeamName = ko.observable(data.AwayTeamName);
  this.AwayBeerAdjustedPrice = ko.observable(data.AwayBeerAdjustedPrice);
  this.AwayBeer = ko.observable(data.AwayBeer);
  this.awayTeamImage = ko.observable(data.AwayTeamImage);
  this.FullScore = ko.computed(function() {
    return data.HomeTeamScore + " | " + data.AwayTeamScore;
  }, this);
}


function vm() {
  var self = this;
  self.gameCollection = ko.observableArray([]);
  ko.applyBindings(this);
}


getGames = function() {
  $.ajax({
    type: "GET",
    dataType: "json",
    // placeholder:
    url: 'data:application/json;utf8,[]',
    //url: "/Dashboard/PopulateMonitor/",
    error: errorFunc,
    success: function(data) {
      _vm.gameCollection.removeAll();
      $.each(data, function() {
        _vm.gameCollection.push(new Board(this));
      });
    }
  });

  function errorFunc() {
    alert("Error, could not load gameboards");
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

两件事:

  • 您不应多次调用 applyBindings。所以,把它移到你的 setTimeout 之外。

  • _vm.gameCollection = [] 将不起作用。要清除 observableArray,请使用 removeAll。您也可以像这样将它设置为一个空数组:_vm.gameCollection([])

  • 此外,如果你想在一段时间后调用同一个函数,你可以使用setInterval

这是您的代码的最小版本。单击 Run code snippet 进行测试。我创建了一个 counter 变量,它每秒用新的 data 更新 gameCollection

let counter = 0;

function refreshPage() {
  getGames();
  console.log("Page refreshed");
};

function Board(data) {
  this.gameChannel = ko.observable(data.GameChannel);
}

function vm() {
  var self = this;
  self.gameCollection = ko.observableArray([]);
}

getGames = function() {
  let data = [
  {
     GameChannel: `GameChannel ${++counter}`
  },
  {
     GameChannel: `GameChannel ${++counter}`
  }];

  _vm.gameCollection.removeAll(); // <- Change here
  
  data.forEach(function(item) {
    _vm.gameCollection.push(new Board(item));
  });
}

var _vm = new vm();
ko.applyBindings(_vm); // this needs to be only called once per page (or element)

setInterval(refreshPage, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<!-- ko foreach: gameCollection -->
<span data-bind="text: gameChannel"></span><br>
<!-- /ko -->