Simple binding
First, we first define a ViewModel
Copy Code code as follows:
var Appviewmodel = {
ShouldShowMessage:ko.observable (True)///the div is visible when initialized
};
Appviewmodel.shouldshowmessage = Ko.observable (false); Now, hidden.
Ko.applybindings (Appviewmodel);
And activate the knockout via Ko.applybindins.
Then define a UI interface element
Copy Code code as follows:
<div data-bind= "Visible:shouldshowmessage" >
You'll be here when "Shouldshowmessage" holds a true value.
</div>
After running, the div is displayed when initialized, and then it is reset to false, causing the div to be hidden.
Parameters:
When the parameter is set to a false value (for example: Boolean false, numeric value 0, or null, or undefined), the binding sets the element's Style.display value to none, leaving the element hidden. It takes precedence over any display style you define in CSS.
When the parameter is set to a truth value (for example, a Boolean value of true, or a Non-empty Non-null object or array), the binding deletes the element's Style.display values and makes the element visible. And then you customize the display style in CSS will automatically take effect.
If the parameter is a monitor attribute observable, the visible state of the element will change depending on the value of the parameter, and if not, the visible state of the element will be set once and not later.
Use a function or an expression to control the visibility of an element
You can also use a JavaScript function or an expression as an argument. In this case, the result of the function or expression will determine whether to show/hide the element. For example:
Copy Code code as follows:
<script type= "Text/javascript" >
var Appviewmodel = {
ShouldShowMessage:ko.observable (True),///is initialized when the div is visible
MyValues:ko.observableArray ([])
};
Appviewmodel.shouldshowmessage = Ko.observable (false); Now, hidden.
AppViewModel.myValues.push ("some value"); Add an item to the Myvalues array
Ko.applybindings (Appviewmodel);
</script>
A Myvalues property value was added to the ViewModel
Add an item to the Myvalues array at the same time
and an element is bound in the page UI
Copy Code code as follows:
<div data-bind= "visible:myvalues (). length > 0" >
You'll be myvalues ' has at least one.
</div>
That's it. When the "some value" element is added, myvalues () length>0 The result is true
Then this div will show up.