knockout if bindings with boolean not evaluating correctly
javascript, knockout-2.0, knockout.js, mvvm
Solution
If your `IsEditing` an observable the `if` binding should evaluate it correctly.
However the `if` binding should be applied on "container like" elements e.g. on elements which can have child elements.
The documentation a little bit confusing and talks about contained markup:
The if binding, however, physically adds or removes the contained markup in your DOM,
Because the `input` cannot have child elements the `if` cannot remove anything from the `input`. You need to wrap your `input` into a `div` and apply there the `if` or you can use the container-less binding syntax:
<!-- ko if: IsEditing -->
<input type="text" id="SystemName" data-bind="{ value: SystemName }" />
<!-- /ko -->
Demo JSFiddle.
Problem
I have the following in my view, using a span to show a readonly view and an input to show an edit view. ``` <span data-bind="{ ifnot:IsEditing, text:SystemName }"></span> <input type="text" id="SystemName" data-bind="{ if:IsEditing, value:SystemName }" /> ``` The IsEditing observable is evaluating to false. I'm returning JSON that has the following hierarchy. ``` Project . . Systems (collection) SystemName ``` I'm loading the value in via JQuery, creating the observable model using the following: ``` $.ajax({ type: "get", url: "..", success: function (d) { var pList = []; for (var p = 0, plen = d.Data.length; p < plen; p++) { var proj = d.Data[p]; var systems = proj.Systems; var sList = []; proj = ko.mapping.fromJS(proj); for (var s = 0, slen = systems.length; s < slen; s++) { sList.push(ko.mapping.fromJS(systems[s])); } proj.Systems = ko.observableArray(sList); pList.push(proj); } window["model"].projects(pList); }, error: function (e) { debugger; alert("An error occurred"); } }); ``` On load, whenever the model is loaded and this expression is evaluated, both elements always show up, instead of showing the span and hiding the input. When I change this to the visible binding, only the span shows. Why is the input showing with the if binding, when IsEditing is evaluating to false?