if binding purpose
If binding is generally the format is data-bind=if:attribute. The value of the attribute or expression followed by if should be a bool value (can also be a non-bool value, and true when a non-empty string). The function of if binding is similar to that of visible binding. It can control the display and hiding of DOM. The difference is that if binding is physically deleting or adding DOM elements.
Example 1
This example shows the dynamic deletion of IF binding to add DOM:
Display message
UI source code:
<label><input type="checkbox" data-bind="checked: displayMessage" /> Display message</label> <div data-bind="if: displayMessage">Here is a message. Astonishing.</div>
View model source code:
({ displayMessage: (false) });
Example 2
In this example, the loop planets is bound by foreach to monitor the property array, where capital is null in the project whose name is Mercury, then the project in the loop only displays its name.
<ul data-bind="foreach: planets"> <li> Planet: <b data-bind="text: name"> </b> <div data-bind="if: capital"> Capital: <b data-bind="text: "> </b> </div> </li> </ul> <script> ({ planets: [ { name: 'Mercury', capital: null }, { name: 'Earth', capital: { cityName: 'Barnsley' } } ] }); </script>
Note: Use containerless if binding (if virtual binding)
Like the previous virtual binding, it is also performed using <!-- ko --> and <!-- /ko -->. Virtual binding is suitable for situations where UI elements are not changed.
<ul> <li>This item always appears</li> <!-- ko if: someExpressionGoesHere --> <li>I want to make this item present/absent dynamically</li> <!-- /ko --> </ul>
ifnot binding
ifnot binding is a reverse expression of if binding, and the format is the same as if binding, but the judgment result is the opposite of if. Just like equal to and not equal to. For example:
<div data-bind="ifnot: someProperty">...</div>
The equivalent writing method is:
<div data-bind="if: !someProperty()">...</div>
Some people would say that using if binding is enough. For hair, you also need ifnot to bind. The reason is that many people with obsessive-compulsive disorder like this ifnot binding method, which looks easier to understand and the code is cleaner.
The above is the KnockoutJS API Chapter 4 of the data control flow if binding and ifnot binding are introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!