2. Knockout’s declarative binding system
provides a concise and powerful way to
link data to the UI.
Binding syntax
Today's message is: <span data-bind="text: myMessage"></span>
A binding consists of two items, the binding name and value,
separated by a colon. Here is an example of a single, simple
binding:
3. 1. The visible binding
2. The text binding
3. The html binding
4. The css binding
5. The style binding
6. The attr binding
4. Purpose
• The visible binding causes the associated DOM element to
become hidden or visible according to the value you pass to the
binding.
Example
<div data-bind="visible: shouldShowMessage">
You will see this message only when "shouldShowMessage" holds a
true value.
</div>
<script type="text/javascript">
var viewModel = {
shouldShowMessage: ko.observable(true) // Message initially visible
};
viewModel.shouldShowMessage(false); // ... now it's hidden
viewModel.shouldShowMessage(true); // ... now it's visible again
</script>
5. Purpose
• The text binding causes the associated DOM element
to display the text value of your parameter
Example
Today's message is: <span data-bind="text: myMessage"></span>
<script type="text/javascript">
var viewModel = {
myMessage: ko.observable() // Initially blank
};
viewModel.myMessage("Hello, world!"); // Text appears
</script>
6. Purpose
• The html binding causes the associated DOM element to
display the HTML specified by your parameter.
Example
<div data-bind=“html: details “></div>
<script type="text/javascript">
var viewModel = {
details : ko.observable()
};
viewModel. details(“<em>Hello, world!<em>”);
</script>
7. Purpose
• The css binding adds or removes one or more named CSS
classes to the associated DOM element. This is useful, for
example, to highlight some value in red if it becomes negative.
Example
<div data-bind=“css: { profitWarning: currentProfit() < 0 }“> Profit
Information </div>
<script type="text/javascript">
var viewModel = {
currentProfit : ko.observable(20000)
};
viewModel.currentProfit(-15);
</script>
8. Purpose
• The style binding adds or removes one or more style values to
the associated DOM element. This is useful, for example, to
highlight some value in red if it becomes negative, or to set the
width of a bar to match a numerical value that changes.
Example
<div data-bind=“style: { color: currentProfit() < 0 ? 'red' : 'black' }“> Profit
Information </div>
<script type="text/javascript">
var viewModel = {
currentProfit : ko.observable(20000)
};
viewModel.currentProfit(-15);
</script>
9. Purpose
• The attr binding provides a generic way to set the
value of any attribute for the associated DOM element.
Example
<a data-bind=“attr: { href: url, title: details}“> Report </a>
<script type="text/javascript">
var viewModel = {
url: ko.observable("year-end.html"),
details: ko.observable("Report including final year-end statistics")
};
</script>
10. You see, God helps only people who work hard.
That principle is very clear.
- A. P. J. Abdul Kalam