0

I was wondering if there is a way in knockout to create dom items, similar to how the foreach binding works, using an observable with only an integer?

eg

var viewModel = function(){
    this.item = ko.observableArray(["1","2","3"]);

    }

this will create 3 dom elements when using foreach binding. Where I would like to see the following produce three dom items.

 var viewModel = function(){
        this.item = ko.observable(3);

        }

one addition is that the end result needs to be dynamic so if the value changes the dom items would too.

SANN3
  • 9,459
  • 6
  • 61
  • 97
Mark Hollas
  • 1,107
  • 1
  • 16
  • 44

1 Answers1

0

Artem Vyshniakov's answer is very good but is mainly useful when you don't data bound to those created elements.

If you need to create elements based on a count but they also have data coming from an array then to create a limit count:

var data = [{ "Name": "John", "Age" : 20 },{ "Name": "Mike", "Age" : 30 },{ "Name": "Tom", "Age" : 40 },{ "Name": "Sam", "Age" : 50 }];

function vm(){
    var self = this;
    self.itemCount = ko.observable(3);
    self.items = ko.observableArray(data);
    self.limitedItems = ko.computed(function(){
        var ctr = 0;
        return ko.utils.arrayFilter(self.items(), function(item){
            ctr++
            return ctr <= self.itemCount() ? item : false;
        });
    });
}

ko.applyBindings(new vm());

So you can control the number of elements from the collection:

<input data-bind="value: itemCount, valueUpdate: 'afterkeydown'" />

<ul data-bind="foreach: limitedItems">
    <li data-bind="text: Name + ', ' + Age"></li>
</ul>
makeitmorehuman
  • 11,287
  • 3
  • 52
  • 76