Search code examples
knockout.jsko.observablearray

knockout foreach based on another observable


I have an an observable and few observable arrays. I want to iterate of of these observable arrays depending on what observable do I have. How cryptic does it sound. If it is, than this fiddle will make it super simple

function VM(){
    var self = this;
    this.type1 = ko.observableArray(['Hello', 'this', 'is', 'first', 'array']);
    this.type2 = ko.observableArray(['Second', 'Array']);
    this.type3 = ko.observableArray(['hohoho', 'hahaha']);

    this.type = ko.observable('type1')

    this.setType = function(t){
        self.type(t);
    }
}

ko.applyBindings(new VM())

So depending on which button do I click, I want different arrays to be iterated.

<button data-bind="click: function(){setType('type1')}">Type1</button>
<button data-bind="click: function(){setType('type2')}">Type2</button>
<button data-bind="click: function(){setType('type3')}">Type3</button>

<div data-bind='text: type'></div><br>

<ul data-bind="foreach: type1">
    <li data-bind="text: $data">
</ul>

As you see, clicking on the button change observable, but I can not change array which will be iterated. How can I achieve that?


Solution

  • Modify your ul to look like this:

    <ul data-bind="foreach: $root[type()]">
        <li data-bind="text: $data">
    </ul>
    

    $root is supplied by knockout, and refers to the object originally specified to the ko.applyBindings call.