Answer: <html>
<head>
<title> Simple hello world example </title>
<script language="javascript" type="text/javascript" src = "knockout-1.2.0.js"></script>
</head>
<body>
<p>Enter a name <input data-bind="value:name"/></p>
<button data-bind="click:buttonCommand">Say hello</button>
<script type="text/javascript">
// View model
var viewModel = {
name : ko.observable(""),
buttonCommand : function() {
alert('Hello ' + this.name() + ', welcome to knockout');
}
};
// This makes Knockout to work
ko.applyBindings(viewModel);
</script>
</body>
</html>
Code Explanation
We have a textbox control as well a button control in the view.
In the View Model, we have two properties namely name and buttonCommand. The buttonCommand is bound to the button control while the name property is to the textbox control. The ko.observable is use to assign the value to the property. The reason is that, the model properties are declared as observables which notifies the subscribers about changes and can automatically detect dependencies. Henceforth, whenever the user enters his/her name in the textbox and clicks on the button, the value that is being assigned to the name property is read and is displayed to the browser.
Also the observable properties need some attention. The values are set or get from the properties through methods. This is to ensure the cross browser compatibility since the getters and setters are not understandable by many browsers.
The data-bind attribute binds the view models properties to the view and the communication sails between these two.
We need to activate Knockout to take effect of the data-bind attribute which is a non native Html attribute. For this reason, we need to call the ko.applyBindings (ViewModel). The first parameter to the applyBindings should be the view model; There is an optional second parameter and if specified should be a DOM node e.g. ko.applyBindings(viewModel, document.getElementById('ElementID')).
Asked In: Many Interviews |
Alert Moderator