Knockout.js "if Binding" on multiple booleans
Asked Answered
G

3

39

Is it possible to use Knockout's if binding on more than one boolean?

Such as

<div data-bind="if: (property.aTrueValue && property.anotherTrueValue)">...

I've tried a lot of different syntax, but can't seem to find the right syntax. I'm not sure it's even possible.

Giacopo answered 9/3, 2013 at 5:22 Comment(1)
jsfiddle.net/daedalus28/6hxvQGabar
S
55

When Knockout processes your bindings it first evaluates your expression.

If the expression results in an observable, it then evaluates the observable as a convenience to get the final value that the if: works on.

So the two following work identically

<div data-bind="if: foo"></div>
<div data-bind="if: foo()"></div>

Once you leave the world of simple expressions ending in an observable, you probably also want to leave the sugar behind and always evaluate the observables yourself (for sanity if nothing else).

Try the following

<div data-bind="if: (property.aTrueValue() && property.anotherTrueValue())">...
Santa answered 9/3, 2013 at 5:34 Comment(0)
H
6

You can - the if binding just takes an arbitrary expression. When doing more than just referencing the value of an observable like that, you'll need to actually call the observable like so:

<div data-bind="if: (property.aTrueValue() && property.anotherTrueValue())">...

Here's a working jsfiddle.

Hoppe answered 9/3, 2013 at 5:37 Comment(0)
L
0

Current solution is more like this:

<div data-bind="if: (prop() === true && prop2() === true)">...
Landgravine answered 12/6, 2020 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.