With a simple example explain Knockout

 Posted by Niladri.Biswas on 12/13/2012 | Category: Others Interview questions | Views: 3886 | Points: 40


<title> Simple hello world example </title>
<script language="javascript" type="text/javascript" src = "knockout-1.2.0.js"></script>
<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

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 

Comments or Responses

Login to post response