从Javascript删除observableArray中清除所有元素。物品仍然造成重复

时间:2018-12-15 18:21:54

标签: javascript knockout.js

我正在尝试创建一个由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

2 个答案:

答案 0 :(得分:0)

每次调用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>

答案 1 :(得分:0)

事物的结合:

  • 您不应多次致电applyBindings。因此,将其移至setTimeout之外。

  • _vm.gameCollection = []不起作用。要清除observableArray,请使用removeAll。您还可以将其设置为一个空数组,如下所示:_vm.gameCollection([])

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

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

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