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.
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.
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.
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.
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/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With