How to use the Knockout text binding DOM

  • 2020-03-29 23:46:19
  • OfStack

Simple binding

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 sets the parameter value on the element's innerText (IE) or textContent (Firefox and other similar browsers) properties. The original text will be overwritten.
If the parameter is monitoring the observable, the element's text text is updated as the parameter value changes. If not, the element's text text is set only once and is not updated later.
If you pass a number or a string (such as an object or an array), the text will be the equivalent of yourparameter.tostring ().
Use functions or expressions to determine the text value
Continue to add a property to the ViewModel above, and add a dependency monitoring property

price: ko.observable(24.95)
    viewModel.priceRating = ko.dependentObservable(
        function () {
         return this.price() > 50 ? "expensive" : "affordable";
        }, viewModel);

Add a UI page element for binding

The item is <span data-bind="text: priceRating"></span> today.

Now, the text text will be replaced between "expensive" and "affordable," depending on how the price changes.
HTML encoding
Because the binding sets 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:

viewModel.myMessage("<i>Hello, world!</i>");

Instead of displaying italics, it outputs the label as it is. If you need to display HTML content, refer to the HTML binding.
Whitespace whitespace for IE 6
IE6 has a strange problem. If there is a space in span, it will automatically become an empty span. Knockout doesn't work if you want to write the following code.

Related articles: