Knockout.js “if Binding” on multiple booleans

吃可爱长大的小学妹 提交于 2019-12-10 12:28:00

问题


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.


回答1:


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())">...



回答2:


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.



来源:https://stackoverflow.com/questions/15307504/knockout-js-if-binding-on-multiple-booleans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!