MrB
MrB

Reputation: 1594

Knockout change models in template

First I'm new to using knockout.

I have bound array1 to my template now I would like change it to use array2 is this possible with knockout?

What I was messing with

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

Upvotes: 0

Views: 134

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134811

Create a computed observable that will return one of the two arrays based on your conditions whatever they would be and bind to it. Make sure that the conditions that decide which to choose are also observable so it will update properly.

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>

Of course the logic could be more complex than that. To be more manageable, I would make the condition observable computed as well and create the logic in there. The computed observable that returns the array wouldn't have to change much.

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

Upvotes: 2

Related Questions