Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does negating a bind value in knockoutjs have to be unwrapped

Tags:

knockout.js

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.

like image 416
jaffa Avatar asked Feb 23 '12 10:02

jaffa


1 Answers

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

like image 57
Romanych Avatar answered Nov 18 '22 16:11

Romanych