If binding purpose
The if binding is typically the value of a property or expression after the format is data-bind=if:attribute,if should be a bool value (or it can be a non-bool value, or True if it is not an empty string), and the if binding acts like the visible binding. You can control the display and hiding of the DOM, not the same thing, if the binding is to physically delete or add DOM elements.
Example 1
This example shows the dynamic deletion of the IF binding add DOM:
Display messageHere is a message. Astonishing.
UI Source code:
< label >< type= "checkbox" data-bind= "Checked:displaymessage"/> Display message</label><data-bind = "If:displaymessage">here is a message. Astonishing. </ Div >
View Model Source code:
ko.applybindings ({ displayMessage:ko.observable (false)});
Example 2
In this example, the loop planets monitors an array of properties through a foreach binding, where capital is null in a project whose name is Mercury, and the item in the loop displays only its name.
<ulData-bind= "Foreach:planets"> <Li>Planet:<bData-bind= "Text:name"> </b> <DivData-bind= "If:capital">Capital :<bData-bind= "Text:capital.cityName"> </b> </Div> </Li></ul> <Script>Ko.applybindings ({planets: [{name:'Mercury', Capital:NULL}, {name:'Earth', capital: {cityname:'Barnsley' } } ] });</Script>
Note: Use a container-free if binding (if virtual binding)
Like the previous virtual bindings, the same use <!-- ko -->
and<!-- /ko -->进行。虚拟绑定适用于不改变UI元素的情况。
<ul> <Li>This item is always appears</Li> <!--ko if:someexpressiongoeshere - <Li>I want to make this item present/absent dynamically</Li> <!--/ko -</ul>
Ifnot binding
The ifnot binding is the inverse expression of the if binding, in the same format as if binding, except that the result is the opposite of the If. Just as equals and not equal. For example:
<data-bind= "Ifnot:someproperty">... </ Div >
The equivalent notation is:
<data-bind= "if:!someproperty ()">... </ Div >
Some would say that using the if binding is enough. For Mao also to Ifnot binding. The reason is that there are many obsessive-compulsive patients who like the ifnot binding, seem more understandable, and the code is cleaner.
Knockoutjs 3.X API Chapter Fourth data binding (3) control flow if binding and ifnot binding