Simple binding
Copy codeThe Code is as follows:
Today's message is: <span data-bind = "text: myMessage"> </span>
<Script type = "text/javascript" src = "~ /Scripts/knockout-2.3.0.debug.js "> </script>
<Script type = "text/javascript">
Var viewModel = {
MyMessage: ko. observable ()
};
ViewModel. myMessage ("Hello, world! ");
Ko. applyBindings (viewModel );
</Script>
KO sets the parameter value to the innerText (IE) or textContent (Firefox and other similar browsers) attributes of the element. The original text will be overwritten.
If the parameter is the monitored attribute observable, the text of the element will be updated based on the change of the parameter value. If not, the text of the element will be set only once and will not be updated later.
If you pass a number or string (such as an object or an array), the displayed text will be equivalent to yourParameter. toString.
Use a function or expression to determine the text value
Add a property in the ViewModel above and add a dependency monitoring property.
Copy codeThe Code is as follows:
Price: ko. observable (24.95)
ViewModel. priceRating = ko. dependentObservable (
Function (){
Return this. price ()> 50? "Expensive": "affordable ";
}, ViewModel );
Add a UI page element for binding
Copy codeThe Code is as follows:
The item is <span data-bind = "text: priceRating"> </span> today.
Now, text will be replaced between "expensive" and "affordable", depending on how the price changes.
About HTML encoding
Because the binding is to set the innerText or textContent of the element (instead of innerHTML), it is safe and there is no risk of HTML or script injection. For example, if you write the following code:
Copy codeThe Code is as follows:
ViewModel. myMessage ("<I> Hello, world! </I> ");
It does not display italics, but outputs labels as is. If you want to display HTML content, see html binding.
Whitespace of IE 6
IE6 has a strange problem. If there is space in the span, it will automatically become an empty span. If you want to write the following code, Knockout will not be of any effect.