-1

In case I do:

data-bind="attr: {'id': $index}"

than IDs are 0, 1, 2... but if I do:

data-bind="attr: {'id': $index>0 ? 'choice'+$index : 'choice'}"

than ID is always 'choice', what do I do wrong?

It is Knockout v3.4.2

2

1 Answer 1

2

$index is actually an observable. In a simple binding, knockout will handle it automatically. In a more complex expression, it doesn't, you need to manually call it:

data-bind="attr: {'id': $index()>0 ? 'choice'+$index() : 'choice'}"

They all end up with just 'choice', because $index>0 will always evaluate to false, since it's comparing the text representation of the $index observable function with 0. This function starts with f and "f" > 0 is false.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, that makes sense and it works. But I have never found docs about 'simple' and 'complex' binding, always had problems with that :(
@skobaljic Just think of anything other than an observable by itself (as per your first example) as "complex".
I get it, no problems, but never find explanation in docs, was something I had to figure myself. Is there any docs about it? Something that says: If you bind observable only, than you need no brackets?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.