Knockout在模板中更改模型

时间:2013-01-13 05:56:09

标签: javascript knockout.js

首先,我是新手使用淘汰赛。

我已将array1绑定到我的模板现在我想将其更改为使用array2这是否可以使用knockout?

我在搞什么?

  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());

1 个答案:

答案 0 :(得分: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不需要改变太多。

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);
}