Question

I would like to bind a visible property to be true when one of two conditions are true. Something like the following

 <tr data-bind="visible: active || $parent.displayDeactive">....</tr>

My code works when I do one or the other bindings but not when I put the || in there. I haven't found any documentation that says I can put any logic in this binding, but if I can't do it directly what is the est way to do it since I am binding a property of a template and one object of the $parent viewmodel.

Was it helpful?

Solution

If you are using the value of an observable in an expression then you need to reference them as a function. So, if active and displayDeactive are observables you would do:

data-bind="visible: active() || $parent.displayDeactive()"

There are a few ways to move it to the view model, you could:

  • create a computed observable on the child (function would need to be able to reference the parent)
  • create a function on the parent that takes in the child and returns your value (bindings are executed in a computed observable, so it will fire again when any observable that it accesses changes)
  • create a function on the child that takes in the parent and returns the value (same note as above)

Sample of logic in the binding and using a function on the parent here: http://jsfiddle.net/rniemeyer/f6ZgH/

OTHER TIPS

Add the parens after the observables, since you are evaluating them.

<input type="checkbox" data-bind="checked:displayDeactive"> Display deactive</input>
<br/><br/>
<table>
    <tbody data-bind="foreach: products">
        <tr data-bind="visible: active() || $parent.displayDeactive()">
            <td><span data-bind="text:name"></span></td>
        </tr>
    </tbody>
</table>

You can find the full code here: http://jsfiddle.net/johnpapa/gsnUs/

You could use a computed property on the templated item that evaluates the expression (just saw the @RPNiemeyer responded with that too ... I +1'd).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top