Chapter 2. The Ins and Outs of Data Binding

Binding HTML Data

In Example 1-1, text was data-bound to a span tag. Like text, it’s quite common to data-bind content that contains HTML data.

In Example 2-1, the getName function is expanded to wrap the output of the name data binding with some HTML code.

HTML Versus Text Binding

HTML bindings work similarly to text with the exception that they render any HTML tags provided. If you were to use the text binding with HTML content, the HTML would be escaped, and the content would be displayed as text.

In Example 2-1, I update two things. First, the data-bind attribute is moved from the span tag to the h1 tag. Second, it is bound to the getName function, which has been updated to contain some HTML code.

Example 2-1. h1 tag with HTML binding
<!DOCTYPE html>
<html>
<head> 
    <title>Data Binding with KnockoutJS</title>
</head>
<body> 

    <h1 data-bind="html: getName()"></h1> 

    <script type='text/javascript' src='js/knockout-3.2.0.js'></script> 
    <script> 
        function ViewModel() { 

            var self = this; 

            self.name = 'Steve Kennedy'; 

            self.getName = function() { 
                return 'Hello <em>' + self.name + '</em>!'; 
            }; 
        }; 

        var viewModel = new ViewModel();
        ko.applyBindings(viewModel); 
    </script>
</body>
</html>

Running Example 2-1 would output a similar message to Example 1-1, with the exception that the name would be italicized because of the HTML tag around the output of the name property.

Binding HTML Attributes, CSS Classes, and CSS Styles

Knockout can bind almost ...

Get Knockout.js now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.