How can I access the foreach index when iterating through ko.computed in knockout.js

I create a client-side paged list with knockout.js and im trying to infer the page index using the code below, so I get interactive links with numbers so people can switch the page.

<ul data-bind="foreach:Paging"> <li> <a href="#" data-bind="click: $root.SetCurrentPage(), text: WHATTOWRITEHERE "></a> </li> </ul> 

In my view model

 this.Paging = ko.computed(function () { return ko.utils.range(1, this.TotalPages); }); 

Everything works, I tried only the output of the text: test and he writes a test for each page, but I want numbers. So the easiest way is, of course, accessing the current index in foreach and + 1.

How can I do this?

+4
source share
2 answers

The problem may be with your computed co. You did not bind it to this . Therefore, instead of:

 this.Paging = ko.computed(function () { return ko.utils.range(1, this.TotalPages); }); 

.. try ...

 this.Paging = ko.computed(function () { return ko.utils.range(1, this.TotalPages); }, this); 

Then you can try the ColinE text: this sentence

+2
source

When you use this in bindings, it will refer to the window object. You should use $data as follows:

 <a href="#" data-bind="click: $root.SetCurrentPage(), text: $data"></a> 

I tested it using this markup and it worked as expected:

 <!-- returns 12345678910 --> <div data-bind="foreach: ko.utils.range(1,10)"><span data-bind="text: $data"></span></div> 
+2
source

Source: https://habr.com/ru/post/1392024/


All Articles