0

首先,我不熟悉使用淘汰赛。

我已将 array1 绑定到我的模板,现在我想将其更改为使用 array2,这可能与淘汰赛有关吗?

我在搞什么

  var viewModel = function(){
    var _this = this;
    this.test = [{ name: 'Fruit4'}, {name: 'Vegetables'}];
    this.categories = ko.observableArray(this.test);
    this.changeItems = function()
    {
       this.test= [{ name: 'Fruit2'}, {name: 'Vegetables2'}];
       categories = ko.observableArray(this.test);     
    }
  };

  ko.applyBindings(viewModel());
4

1 回答 1

2

创建一个计算的 observable,它将根据您的条件返回两个数组之一,无论它们是什么并绑定到它。确保决定选择哪个的条件也是可观察的,以便正确更新。

function ViewModel(data) {
    this.array1 = ko.observableArray(data.array1);
    this.array2 = ko.observableArray(data.array2);

    // change this value to true to use array2
    this.chooseArray2 = ko.observable(false);

    this.array = ko.computed(function () {
        return this.chooseArray2()
            ? this.array2()
            : this.array1();
    }, this);
}
<div data-bind="foreach: array">
    ...
</div>

当然,逻辑可能比这更复杂。为了更易于管理,我还将计算条件 observable 并在其中创建逻辑。返回数组的计算 observable 不必改变太多。

function ViewModel(data) {
    this.array1 = ko.observableArray(data.array1);
    this.array2 = ko.observableArray(data.array2);

    // which to choose depends on a number of conditions
    this.someCondition = ko.observable(false);
    this.anotherCondition = ko.observable(true);
    this.someNumber = ko.observable(132);
    this.chooseArray2 = ko.computed(function () {
        // some complex logic
        if (this.someNumber() < 0) {
            return this.someCondition();
        }
        return this.someCondition() || !this.anotherCondition();
    }, this);

    this.array = ko.computed(function () {
        return this.chooseArray2()
            ? this.array2()
            : this.array1();
    }, this);
}
于 2013-01-13T08:52:24.547 回答