I've noticed that in KnockoutJS that value binding doesn't work if it is negated:
like so:
data-bind="showTip: enableTip, css: { disabled: !addButtonEnabled }"
doesn't correctly pickup the negated addButtonEnabled variable.
However, this does work:
data-bind="showTip: enableTip, css: { disabled: !addButtonEnabled() }"
Why is it that this has to be unwrapped, where the other doesn't?
I'm using knockout 1.2.1.
Let me explain a bit how KO parse bindings in your example.
In fact data-bind contains JSON. KO wraps it with {} symbols and evaluate as normal JS code. In your example KO got this object after evaluation:
{
showTip: enableTip,
css: { disabled: !addButtonEnabled }
}
css
bindingHandler receives node binding should be applied to and bindingAccessor function.
After evaluation of this function we get an "argument" for css
binding. which is equal to object
{ disabled: !addButtonEnabled }
Then css
bindingHandler iterates through properties of this object to set corresponding styles. When it comes to disabled
property we need to read value for it.
Usually all standard bindings read value in this way: ko.utils.unwrapObservable(value)
which returns value
if value
is not observable or value stored in this observable variable.
In your case value = !addButtonEnabled
. As you can see !addButtonEnabled
is JavaScript expression, not observable. So it just evaluates this expression. So in fact your button is always enabled since observable() != false
.
In your second case value to be evaluated contains value of observable so it works correct.
I think you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With