Professional Documents
Culture Documents
Knockout JS: Ganesan Chandrasekaran
Knockout JS: Ganesan Chandrasekaran
Ganesan Chandrasekaran
Chapter I
INTRODUCTION
The following line will explain how to include in the HTML project
• <script type='text/javascript' src='knockout-3.4.0.js'></script>
• <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"
type="text/javascript"></script>
...
// function code
...
}, this);
ko.components.register('component-name', {
viewModel: {...}, //function code
template: {....) //function code
});
<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>
• When the parameter resolves to a false-like value (e.g., the boolean value false, or the numeric value 0, or
null, or undefined), the binding sets yourElement.style.display to none, causing it to be hidden. This
takes priority over any display style you’ve defined using CSS.
• When the parameter resolves to a true-like value (e.g., the boolean value true, or a non-null object or
array), the binding removes the yourElement.style.display value, causing it to become visible.
• Note that any display style you’ve configured using our CSS rules will then apply (so CSS rules like x {
display:table-row } work fine in conjunction with this binding).
o If this parameter is an observable value, the binding will update the element’s visibility
whenever the value changes. If the parameter isn’t observable, it will only set the element’s
visibility once and will not update it again later.
o Additional parameters
• None
<script type="text/javascript">
var viewModel = {
myMessage: ko.observable() // Initially blank
};
viewModel.myMessage("Hello, world!"); // Text appears
</script>
<script type="text/javascript">
var viewModel = {
details: ko.observable() // Initially blank
};
viewModel.details("<em>For further details, view the report <a
href='report.html'>here</a>.</em>"); // HTML content appears
</script>
<script type="text/javascript">
var viewModel = {
currentProfit: ko.observable(150000) // Positive value, so initially we don't apply the
"profitWarning" class
};
viewModel.currentProfit(-50); // Causes the "profitWarning" class to be applied
</script>
<script type="text/javascript">
var viewModel = {
currentProfit: ko.observable(150000) // Positive value, so initially black
};
viewModel.currentProfit(-50); // Causes the DIV's contents to go red
</script>
<script type="text/javascript">
var viewModel = {
url: ko.observable("year-end.html"),
details: ko.observable("Report including final year-end statistics")
};
</script>