3

我在推入名为“游戏”的可观察数组中的每个项目上重新渲染模板时遇到问题。它是由一个名为“gamesCount”的计算 observable 引起的,它需要向每个人发送订阅以使用新计数更新他们的数组。如果我从代码中删除“gamesCount”,则完全运行得很快。我有 128 个下拉列表与“gamesCount”共享这个数组,并且需要他们更新有多少“游戏”。我怎样才能提高这方面的表现?

app.viewModel.members.bracket = {
        games: ko.observableArray([
            { left: ko.observable(50), top: ko.observable(50), height: ko.observable(96), width: ko.observable(150), reverse: false, type: 1, awayTeam: { display: ko.observable('') }, homeTeam: { display: ko.observable('')} },
            { left: ko.observable(50), top: ko.observable(150), height: ko.observable(96), width: ko.observable(150), reverse: false, type: 1, awayTeam: { display: ko.observable('') }, homeTeam: { display: ko.observable('')} },
            { left: ko.observable(50), top: ko.observable(250), height: ko.observable(96), width: ko.observable(150), reverse: false, type: 1, awayTeam: { display: ko.observable('') }, homeTeam: { display: ko.observable('')} },
            { left: ko.observable(800), top: ko.observable(232), height: ko.observable(426), width: ko.observable(150), reverse: true, type: 1, awayTeam: { display: ko.observable('') }, homeTeam: { display: ko.observable('')} }
        ]),
    };

app.viewModel.members.bracket.gameCount = ko.computed(function () {
        var games = this.games().length;

        var numbers = [];
        for (var i = 0; i < games; i++) {
            numbers.push(i + 1);
        }
            return numbers;

}, app.viewModel.members.bracket);

        <div data-bind="foreach: members.bracket.games">
              @Html.DropDownList("GameNumber", new SelectList(Enumerable.Empty<string>()), new { @class = "select-bracket", data_bind = "options: $root.members.bracket.gameCount, dropdownlist: {}, optionsCaption:' - Game - '" })                      
        </div>
4

1 回答 1

0

关于 DOM 操作和每次更新数组需要创建的 N 2个列表项, Tom 可能是正确的。games您至少可以使用以下方式优化games数组创建:

vm.gameCount = ko.computed(function () {
  var games = this.games().length,
    numbers = new Array(games);

  for (var i = 0; i < games; i++) {
    numbers[i] = i + 1;
  }

  return numbers;
}, vm);

工作的jsFiddle

这可能不如保留游戏 # 数组并仅在计算时对其进行必要的更改那样有效,但它是可读的。

于 2012-07-07T18:38:03.793 回答