In this article post, I am going to share some examples with code for KnockoutJs bindings and other most common requirements and also interview questions and answers.
KnockoutJs Bindings and Others
KnockoutJs Interview Questions and Answers
What Is KnockoutJs? Why We Use?
Knockout is a pure JavaScript library and with the help of KnockoutJs we can create rich and responsive applications. In KnockoutJs, UI (DOM) is directly linked with data model.
If data source of the data model is getting update any time, at the same time the UI (DOM) sections will also get updated automatically.
KnockoutJs is a MVVM design pattern. The MVVM basically know as Model View ViewModel.
By the help of KO, we can implement all functionality more simply manner and works with any server or client-side technology.
Feature of KnockoutJs –
ü Dependency Tracking
ü In the dependency tracking, KnockoutJs automatically update the UI (DOM) when your data model is change.
ü Declarative Binding
ü In the declarative binding, your UI (DOM) is connected to your data model in a simply manner using data-bind control.
What Are the main features of KnockoutJs?
The list of features of KnockoutJs which are -
ü Dependency Tracking
ü Declarative Binding
ü Template Binding
ü Automatic UI (DOM) Refresh
ü Pure JavaScript Library
ü Compact Size
ü Support All Modern Browsers
Dependency Tracking - KnockoutJs make dependency between View and ViewModel. Its track the any changes on dependent objects and it is automatically updating the UI (DOM) when your data models are change.
Declarative Binding - The Declarative Binding provides the ways, your UI (DOM) is connected with your data models in a simply manner using data-bind control.
Template Binding – The Template bindings are used for build sophisticated UI in easily. It’s populate the DOM elements in the nested and repeating manner with the help of for-each, if, with, and other control flow bindings and third party template engine.
Automatic UI (DOM) Refresh – The KnockoutJs automatically refresh the UI (DOM) you’re your ViewModel update. If any changes occurred in the ViewModel data automatically refresh on view/UI/DOM.
Pure JavaScript library – The KnockoutJs works with any client-side or server technology and it is easily works with existing web application without any major changes.
Compact Size – The KnockoutJs size is around 13kb. It is too small and convenient to use.
Support All Modern Browsers – The KnockoutJs support most of the modern browsers like -IE 6+, Firefox 2+, Chrome, Safari, others.
How KnockoutJs different from MVC?
KnockoutJs -
ü KnockoutJs is a MVVM pattern.
ü KnockoutJs work like connected mode.
ü Knockout s supported two types of binding
o One-way binding
o Two-way binding
ü In KnockoutJs, UI part automatically update when your data model update.
ü In KnockoutJs, model part is not directly bind with the view page. Models directly bind with the view-model and view-model directly with the view page.
MVC -
ü MVC is a design pattern.
ü MVC work like disconnected mode.
ü MVC supported only one-way binding.
ü In MVC, not update UI automatically when your data model update. Need event to call data model and update it.
ü In MVC, model parts directly bind with the view page.
How KnockoutJs different from jQuery?
What Is the KO and why we use, explain in details?
What Is the KO and why we use, explain in details?
The KO is a heart and soul of KnockoutJs that provides interdependent way to link the ViewModel to Model and ViewModel to UI (user interface).
The KO does not depend on the jQuery library, but we can use jQuery at the same time. Using KO you can handle client and server side application in simply manner.
What Is observable in Knockout JS?
The Observable is a KnockoutJs property that contains the view model and this property is bind with UI (View) in two way binding.
The Observable is a KnockoutJs property that contains the view model and this property is bind with UI (View) in two way binding.
What Is observable Arrays in Knockout JS?
The Observable array is KnockoutJs properties that contain the item collection in the view model and this property is bind with UI (View) in two way binding.
The Observable array is KnockoutJs properties that contain the item collection in the view model and this property is bind with UI (View) in two way binding.
What Is computed observable?
The Computed observable is a KnockoutJs function which is depends on the other observable properties. Computed function are automatically update when any changes on these dependencies.
The example looks like –
The Computed observable is a KnockoutJs function which is depends on the other observable properties. Computed function are automatically update when any changes on these dependencies.
The example looks like –
//count total draft entries and display on submit button.
self.countTotalDraftEntries = ko.computed(function () {
var sum = 0;
ko.utils.arrayForEach(TimeEntries(), function (key) {
if (key.Status() === 'Draft') {
sum += 1;
}
});
return sum;
});
What Is dependency tracking in KnockoutJs?
In the dependency tracking, KnockoutJs automatically update the UI (DOM) when your data model is change.
In the dependency tracking, KnockoutJs automatically update the UI (DOM) when your data model is change.
What Is indexOf?
Using ArrayIndexOf, find the matched items from array collection. If array items are matched then returns true otherwise returns false.
For Example filter an observable array collection using indexOf () i.e.
var filterAnArrayByArrayIndexOf = function (Text) {
try {
var filterText = Text.toLowerCase();
if (!filterText) {
return selectionList();
}
else {
if (selectionList().length > 0) {
return ko.utils.arrayFilter(selectionList(), function (item) {
if (item.SelectionLabel.toLowerCase().indexOf(filterText) > -1 || item.SelectionDescription.toLowerCase().indexOf(filterText) > -1) {
return true;
}
else {
return false;
}
});
}
}
}
catch (ex) {
window.itk.utility.logExceptions(ex);
}
};
What Type of manipulating in the observable Array?
There are different types of obervableArray manipulations and its looks like-
There are different types of obervableArray manipulations and its looks like-
ü pop()
ü push()
ü shift()
ü unshift()
ü reverse()
ü sort()
ü splice()
ü remove()
ü removeAll()
What types of data binding are available in knockout JS?
There are different types of data bindings and its looks like-
There are different types of data bindings and its looks like-
ü visible binding
ü text binding
ü value binding
ü css binding
ü style binding
ü attr binding
ü template binding
Examples for all above as given below–
CSS binding - If SaveAsDraft is true then icon status images visible margin-left to 30px otherwise visible to 0px.
//HTML
<p data-bind="text: ClientName, style: { marginLeft: SaveAsDraft ? ‘30px’: ‘0px’}"></p>
The ViewModel code looks like –
//view model code
var viewModel = function (Status) {
var self = this;
self.Status = Status;
self.ClientName = ko.observable(‘Anil Singh’);
self.SaveAsDraft = ko.observable(false);
self.SaveAsDraft = ko.computed(function () {
if (self.Status == ‘Draft’) {
return self.SaveAsDraft(true);
}
}, self);
};
ko.applyBindings(new viewModel());
Or other example looks like
//View Code
<div data-bind="style: {display: showHideDiv() ? 'block' : 'none' }">
<!— Need to display your view want to show or hide -->
</div>
//View model Code
<script type="text/javascript">
function myViewModel() {
this.showHideDiv = ko.observable(true);
}
ko.applyBindings(new myViewModel());
</script>
In the above, the myViewModel(){} have showHideDiv() observable is true that means the div is display by default otherwise hide.
If you need to hide to div, that time we can write to -
(this.showHideDiv = ko.observable(false))
Example looks like -
<script type="text/javascript">
function myViewModel() {
this.showHideDiv = ko.observable(false);
}
ko.applyBindings(new myViewModel());
</script>
Computed observable with Value binding -
//HTML Code
<img class="status" src="~/Images/icon_status.png" data-bind="visible: SaveAsDraft" />
<img class="status" src="~/Images/icon_status_red.png" data-bind="visible: SaveAsError" />
If SaveAsDraft is true then icon status images visible otherwise not visible.
If SaveAsError is true then icon status images visible otherwise not visible.
//view model code
var viewModel = function (Status) {
var self = this;
self.Status = Status;
self.SaveAsDraft = ko.observable(false);
self.SaveAsError = ko.observable(false);
self.SaveAsDraft = ko.computed(function () {
if (self.Status == window.itk.model.constant.Draft) {
return window.itk.mytime.viewmodel.SaveAsDraft(true);
}
}, self);
self.SaveAsError = ko.computed(function () {
if (self.Status == window.itk.model.constant.SaveError) {
return window.itk.mytime.viewmodel.SaveAsError(true);
}
}, self);
};
ko.applyBindings(new viewModel());
Text Binding - The text binding is basically used for display matters on end user screens.
<div class="matter">
<h3>Matters List</h3>
<div data-bind="foreach: MattersInMyTimeEntries" >
<h5 data-bind="text: matter.ClientDisplayName"></h5>
<h6 data-bind="text: matter.DisplayName"></h6>
</div>
</div>
Value Binding - The value binding is basically used at the add/edit change event.
<div class="description">
<label>Description</label>
<textarea id="txtDescription"
onkeyup="return checkAbbreviationKey(event)"
data-bind="value: Description, valueUpdate: 'afterkeydown'">
</textarea>
</div>
What Is template binding?
<ul data-bind="template: { name: 'myViewItem', foreach: myItems }"></ul>
How To Creating Custom bindings in knockoutJs?
When we create custom binding, we need to add a property with your custom binding name and assign an object with two callback functions.
Registering your binding - To register a binding, adds it as a sub property of “ko.bindingHandlers” and its looks like.
ko.bindingHandlers.myCustomBinding = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// Set up any your initial state, event handlers, and so on
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// Update the DOM element based on the supplied values.
}
};
DOM elements –
<div data-bind="myCustomBinding : yourValue"> </div>
How To get Row Index in KnockoutJs?
The $index is the KnockoutJs feature and used to point the current items index in array.
The $index is the KnockoutJs feature and used to point the current items index in array.
The $index is an observable, and observable are functions. When you use observable in an expression you must use the () form to access the value.
//HTML Code
<table data-bind="foreach: items">
<tr>
<!--item index in array-->
<td data-bind="text: $index"></td>
<!--item serial number from index-->
<td data-bind="text: $index() + 1"></td>
<td data-bind="text: $data"></td>
<td><a href="#" data-bind="click:
$root.showItemIndex">Show</a></td>
</tr>
</table>
And
//ViewModel
function ViewModel() {
var self = this;
self.items = ko.observableArray([]);
self.showItemIndex = function (item, event) {
/*get current item index*/
var context = ko.contextFor(event.target);
var index = context.$index();
alert('The item index is - ' + index);
};
self.init = function() {
var arr = ['Anil', 'Sunil', 'Sushil', 'Aradhya'];
self.items([]);
self.items(arr);
};
}
And
$(function () {
var vModel = new ViewModel();
ko.applyBindings(vModel);
vModel.init();
});
<!--item index in array-->
<td data-bind="text: $index"></td>
<!--item serial number from index-->
<td data-bind="text: $index() + 1"></td>
I hope you are enjoying with this post! Please share with you friends!! Thank you!!!