具有下拉列表的计算可观察性能

时间:2012-06-30 08:10:21

标签: knockout.js

我遇到的问题是我的模板被重新渲染到每个被推入我的可观察数组中的项目“游戏”。它是由一个名为“gamesCount”的计算可观察引起的,它需要向所有人发送订阅,以使用新计数更新其数组。如果我从代码中删除“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>

1 个答案:

答案 0 :(得分:0)

对于DOM操作以及需要为games数组的每次更新创建的N 2 数量的列表项,Tom可能是正确的。您可以做的最少是使用以下内容优化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);

Working jsFiddle

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