Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using knockout.js, I need a 'count' inside my template

Tags:

knockout.js

Basically, I want to 'label' each row my template produces with a 'line number'

eg.

1 [other html]
2 [other html]
3 [other html]

previously, when adding an object to the array (array used by template), I'd count the array items and then add that count to the new object I'm adding to the array...

BUT, now I need to delete, and it's producing something like this on delete :

1 [other html]
3 [other html]

where '2' has been removed, but really I want it to just label the line numbers and not be an id inside the data in the row. So '3' should disappear and '2' should be the last item, even though '2' was the one.

like image 672
Ninjanoel Avatar asked Mar 22 '12 17:03

Ninjanoel


People also ask

How do I assign a value to knockout observable?

To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.

What is $data in knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel. folders array.

How do I use KnockoutJS in HTML?

It is very easy to use KnockoutJS. Simply refer the JavaScript file using <script> tag in HTML pages. A page as in the following image will be displayed. Click on download link and you will get the latest knockout.


2 Answers

As of knockout 2.1 (maybe before) you can do

<span data-bind="text: $index"></span>

instead of

<span data-bind="text: ko.utils.arrayIndexOf($parent, $data)"></span>

Updated fiddle - http://jsfiddle.net/u9GWr/140/

like image 181
chris vdp Avatar answered Dec 09 '22 19:12

chris vdp


Starting from knockout version 2.1 use $index variable instead of arrayIndexOf method (see this answer for example).


I would use with and $parent for this, example http://jsfiddle.net/u9GWr/139/

Html:

<ul data-bind="with: vm.items">
    <!-- ko foreach: $data -->
    <li><span data-bind="text: ko.utils.arrayIndexOf($parent, $data)"></span>
        <span data-bind="text: name"></span>
    </li>
    <!-- /ko -->
</ul>

JavaScript

vm = {
    items: ko.observableArray( [
        {name: ko.observable("a")},
        {name: ko.observable("b")},
        {name: ko.observable("c")},
    ])
}

ko.applyBindings(vm);

vm.items.splice(2,0, { name: ko.observable('test')});
​

Output

0 a

1 b

2 test

3 c

like image 43
Artem Avatar answered Dec 09 '22 20:12

Artem