Skip to main content

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?
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.

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. 




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 –
//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.

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-

ü  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-
ü  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 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!!!
By Anil Singh | Rating of this article (*****)

Popular posts from this blog

nullinjectorerror no provider for httpclient angular 17

In Angular 17 where the standalone true option is set by default, the app.config.ts file is generated in src/app/ and provideHttpClient(). We can be added to the list of providers in app.config.ts Step 1:   To provide HttpClient in a standalone app we could do this in the app.config.ts file, app.config.ts: import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; import { provideClientHydration } from '@angular/platform-browser'; //This (provideHttpClient) will help us to resolve the issue  import {provideHttpClient} from '@angular/common/http'; export const appConfig: ApplicationConfig = {   providers: [ provideRouter(routes),  provideClientHydration(), provideHttpClient ()      ] }; The appConfig const is used in the main.ts file, see the code, main.ts : import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from '

39 Best Object Oriented JavaScript Interview Questions and Answers

Most Popular 37 Key Questions for JavaScript Interviews. What is Object in JavaScript? What is the Prototype object in JavaScript and how it is used? What is "this"? What is its value? Explain why "self" is needed instead of "this". What is a Closure and why are they so useful to us? Explain how to write class methods vs. instance methods. Can you explain the difference between == and ===? Can you explain the difference between call and apply? Explain why Asynchronous code is important in JavaScript? Can you please tell me a story about JavaScript performance problems? Tell me your JavaScript Naming Convention? How do you define a class and its constructor? What is Hoisted in JavaScript? What is function overloadin

List of Countries, Nationalities and their Code In Excel File

Download JSON file for this List - Click on JSON file    Countries List, Nationalities and Code Excel ID Country Country Code Nationality Person 1 UNITED KINGDOM GB British a Briton 2 ARGENTINA AR Argentinian an Argentinian 3 AUSTRALIA AU Australian an Australian 4 BAHAMAS BS Bahamian a Bahamian 5 BELGIUM BE Belgian a Belgian 6 BRAZIL BR Brazilian a Brazilian 7 CANADA CA Canadian a Canadian 8 CHINA CN Chinese a Chinese 9 COLOMBIA CO Colombian a Colombian 10 CUBA CU Cuban a Cuban 11 DOMINICAN REPUBLIC DO Dominican a Dominican 12 ECUADOR EC Ecuadorean an Ecuadorean 13 EL SALVADOR

25 Best Vue.js 2 Interview Questions and Answers

What Is Vue.js? The Vue.js is a progressive JavaScript framework and used to building the interactive user interfaces and also it’s focused on the view layer only (front end). The Vue.js is easy to integrate with other libraries and others existing projects. Vue.js is very popular for Single Page Applications developments. The Vue.js is lighter, smaller in size and so faster. It also supports the MVVM ( Model-View-ViewModel ) pattern. The Vue.js is supporting to multiple Components and libraries like - ü   Tables and data grids ü   Notifications ü   Loader ü   Calendar ü   Display time, date and age ü   Progress Bar ü   Tooltip ü   Overlay ü   Icons ü   Menu ü   Charts ü   Map ü   Pdf viewer ü   And so on The Vue.js was developed by “ Evan You ”, an Ex Google software engineer. The latest version is Vue.js 2. The Vue.js 2 is very similar to Angular because Evan You was inspired by Angular and the Vue.js 2 components looks like -

55 Best TypeScript Interview Questions and Answers - JavaScript!

What Is TypeScript? By definition, "TypeScript is a typed superset of JavaScript that compiles to plain JavaScript." TypeScript is a superset of JavaScript which provides optional static typing, classes and interfaces. => The TypeScript was first made public in the year 2012. => Typescript is a modern age JavaScript development language. => TypeScript is a strongly typed, object oriented, compiled language. => TypeScript was designed by Anders Hejlsberg (designer of C#) at Microsoft. => TypeScript is both a language and a set of tools. As an Example of TypeScript, class Hello {     msg : string ;      constructor ( message : string ) {          this . msg = message ;      }       getMsg () {          return "Hello, " + this . msg ;      } } TypeScript introduced a great deal of syntax taken from object-oriented programming, including but not limited to: 1) Interfaces 2) Classes 3) Enumerated t