Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout is not evaluating an expression when using $index in a binding

Why is it, that when I try to use knockout.js to bind some text using $index, I get the code of a function instead of a number?

<tbody  data-bind="foreach: MyList">
  <tr>
    <td><span data-bind="text: $index + 1"></span></td>
  </tr>
</tbody>

Instead of getting 1, 2, 3 etc., I get this:

enter image description here

You can see, by the last character in the above image, that my index of zero is being added to 1. If I remove the '+ 1' from my binding, I get 0, 1, 2 instead of the function.

How do I tell knockout to evaluate the expression? I have the same issue when I submit the form. My string fields are being submitted as a function instead of the value.

like image 762
rboarman Avatar asked Jul 02 '12 23:07

rboarman


People also ask

What is binding in knockout?

This binding is used to bind the child elements of an object in the specified object's context. This binding can also be nested with other type of bindings such as if and foreach. Syntax with: <binding-object> Parameters. Pass the object which you want to use as context for binding child elements as the parameter.

Which function is used for computation in knockout?

In some scenarios, it is useful to programmatically determine if you are dealing with a computed observable. Knockout provides a utility function, ko. isComputed to help with this situation. For example, you might want to exclude computed observables from data that you are sending back to the server.

What is a knockout observable?

Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.


2 Answers

$index is an observable, which is a function. Try <span data-bind="text: $index() + 1"></span>

like image 186
John Earles Avatar answered Oct 13 '22 07:10

John Earles


If you use

<span data-bind="text: $index() + 1"></span> 

and for example your index value is 2, the text of your span will be: 21 and not 3.

you should define a function in your viewModel, like this:

self.itemNumber = function(index) {
    return index + 1;
}

and then in your span you should do:

<span data-bind="text: $root.itemNumber($index())"></span>

I hope this will help :)

like image 32
Donatella Avatar answered Oct 13 '22 09:10

Donatella