Simple binding
First define a ViewModel
var AppViewModel = {
shouldShowMessage: ko.observable(true) ///The div is visible during initialization
};
AppViewModel.shouldShowMessage = ko.observable(false); ///Now hidden
ko.applyBindings(AppViewModel);
and activate Knockout through ko.applyBindins.
Then define a UI interface element
You will see this message only when "shouldShowMessage" holds a true value.
After running this div It can still be displayed during initialization, but then it is reassigned to false, causing the div to be hidden.
Parameter:
When the parameter is set to a false value (for example: Boolean value false, numeric value 0, or null, or undefined), the binding will set the style.display value of the element to none, letting The element is hidden. Its priority is higher than any display style you define in CSS.
When the parameter is set to a true value (for example: a Boolean value true, or a non-null object or array), the binding will delete the style.display value of the element and make the element visible. Then the display style you customized in CSS will automatically take effect.
If the parameter is a monitoring attribute observable, the visible state of the element will change according to the change of the parameter value. If not, the visible state of the element will only be set once and will not be updated in the future.
Use functions or expressions to control the visibility of elements
You can also use JavaScript functions or expressions as parameters. In this case, the result of the function or expression will determine whether to show/hide the element. For example:
Adds a property value of myValues in ViewModel
At the same time, adds an item to the array of myValues
and in An element
0">
You will see this message only when 'myValues' has at least one member.
In this way, after adding the "some value" element, myValues().length>0, the result is true
Then this div will be displayed.