ARTICLE

KnockoutJs

  • Dec 10, 2022
  • Com 0
Blog Image

KnockoutJs is a popular JavaScript library that helps developers create dynamic, interactive user interfaces. It is a Model-View-ViewModel (MVVM) framework that allows developers to separate the concerns of the data model, the view, and the view model, making it easier to maintain and test the code.

One of the main advantages of Knockout.js is its ability to automatically update the view based on changes in the data model. This is achieved through a feature called "data binding," which binds the view to the view model and automatically updates the view when the data model changes. This eliminates the need for developers to manually update the view, saving time and reducing the likelihood of errors.

Knockout.js is a powerful JavaScript library that makes it easy to create dynamic, interactive user interfaces. Its data binding and computed observables features make it easy to keep the view in sync with the data model, and its templating feature makes it easy to create and reuse view templates. It is easy to learn and use, and can be easily integrated with other libraries, making it a great choice for building web applications.

Another advantage of Knockout.js is its support for computed observables, which are functions that automatically update when the data they depend on changes. This allows developers to create complex, dynamic views without having to write a lot of boilerplate code.

This also provides a feature called "templating," which allows developers to easily create and reuse view templates. This can help to reduce the amount of code required to create a view and make it easier to maintain.

This is relatively easy to learn and use, even for developers with little or no experience with MVVM frameworks. It has a small footprint and can be easily integrated with other libraries, such as jQuery and Bootstrap, making it a great choice for building interactive web applications.

Features Images

To start Knockout.js, download latest library from official website www.knockoutjs.com copy the file to assets directory and browse the js file into the html file by adding:

<script src="assets/js/knockout-x.x.x.js"></script>
              

To create a view model with KO, just declare any JavaScript object. For example

<script>
 var myViewModel = {
   personName: 'John',
   personAge: 23
 };
</script>
              

You can then create a very simple view of this view model using a declarative binding. For example, the following markup displays the personName value:

The name is  <span data-bind="text: personName"></span>

Properties of Knockout js

  • Observables
    One of the key benefits of KO is that it updates your UI automatically when the view model changes. How can KO know when parts of your view model change? Answer: you need to declare your model properties as observables, because these are special JavaScript objects that can notify subscribers about changes, and can automatically detect dependencies. For example, rewrite the preceding view model object as follows:
    
    <input data-bind='value: personName'/>
    <input data-bind='value: personAge'/>
    
    <script>
    var ViewModel = function (name, age) {
        this.personName = ko.observable(name);
        this.personAge = ko.observable(age);
    };
    ko.applyBindings(new ViewModel("Tom", "26"));
    </script>
                  
  • Computed Observables
    What if you’ve got an observable for firstName, and another for lastName, and you want to display the full name? That’s where computed observables come in - these are functions that are dependent on one or more other observables, and will automatically update whenever any of these dependencies change.
    
    <input data-bind='value: firstName'/>
    <input data-bind='value: lastName'/>
    <span data-bind='text: fullname></span>
    
    <script>
    function ViewModel() {
        this.firstName : ko.observable('jerry');
        this.lastName : ko.observable('tom');
        this.fullname = ko.computed(function(){
        Return this.firstName()+this.lastName();
    },this)
    }
    </script>
                  
  • Subscribers
    These are registered to notify any change in the subscribed properties.
    
    <input data-bind='value: firstName'/>
    <input data-bind='value: lastName'/>
    <span data-bind='text: fullname></span>
    
    <script>
    var ViewModel = function (first, last) {
        this.firstName = ko.observable(first);
        this.lastName = ko.observable(last);
        this.fullName = ko.computed(function(){
        return this.firstName()+this.lastName();
    },this);
    this.firstName.subscribe(function(valueBeforecharge){
        alert(valueBeforecharge)
    },this,'beforeChange')
    };
    
    ko.applyBindings(new ViewModel("tom", "jerry"));
    </script>
                  

Knockout Bindings

Process of ading data from viewModelto the html template

Visible Binding
Element visibility controlled by properties
   
<input data-bind='value: firstName'/>
<input data-bind='value: lastName'/>
<p data-bind='visible:firstName()!=""'>
    First name is: <b><span data-bind='text: firstName'></span></b>
</p>

<script>
var ViewModel = function (first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);
};
ko.applyBindings(new ViewModel("tom", "jerry"));
</script>
              
Text Binding
To display text in an element from associated property.
   
<span data-bind='text: firstName'></span>

<script>
var ViewModel = {
    this.firstName : ko.observable('Tom');
}
</script>
              
HTML Binding
To add html content to an element from associated property. Just like innerHTML() in js.
   
<span data-bind='html: firstName'></span>

<script>
var ViewModel = {
    this.firstName : ko.observable('Tom');
}

ViewModel.firstName("Tom");
</script>
              
CSS Binding
Add or remove CSS class to an element from associated property. In this example, the welcome message will show in green text only if the firstName is not empty.
 
<style type="text/css">
   .active{
    display: block;
    color: green;
   } 
</style>

<span style="display:none" data-bind='css: {active: firstName()!=""'}'> Welcome </span>

<script>
var ViewModel = {
    this.firstName : ko.observable('Tom');
}
</script>
              
Style Binding
Add or remove style values to an element from associated property. In this example, the 'span' text colour will be red if value of firstName is empty and will be green if not empty
 
<span data-bind='style: {color: firstName()!=""?"red":"green"}'> First Name </span>

<script>
var ViewModel = {
    this.firstName : ko.observable('Tom');
}
</script>
              
Attribute Binding
Set attribute values to html elements from associated property. In this example, the 'a' tag will bind with the url
 
<a data-bind='attr: {href: url()}'> First Name </a>

<script>
var ViewModel = {
    this.url: ko.observable('http://www.opsintech.in');
}
</script>
              

Control Flow Bindings

Dealing with controller functions/ conditions
Foreach Binding
Loop data from property array.

<div data-bind="foreach:people">
<span data-bind="text:name"></span>
<span data-bind="text:age"></span>
</div>

<script>
var ViewModel = function () {
this.people = ko.observableArray([
{name:'Tom',age:'24'},{name:'Jerry',age:'30'},{name:'John',age:'29'}
]);
};

ko.applyBindings(); 
</script>
              
If Binding
Can use if condition in binding. In this example, the head tag will bind and show only if condition true

<span data-bind='if: firstName()'>
<h1 data-bind='text:firstName()'></h1>
</span>

<script>
var ViewModel = {
this.firstName : ko.observable('Name');
}

ko.applyBindings(); 
</script>
              
With Binding
Create new binding context of a specified object.

<div data-bind="with:details">
<span data-bind='text:name'></span>
<span data-bind='text:age'></span>
</div>

<script>
var ViewModel = function () {
this.details = {
name: 'Tom',
age: '23'
};
};

ko.applyBindings(); 
</script>
              
Container Less Binding
Binding without using any container elements and without data-bind attribute inside elements. This binding is used in Magento. In this example, the head tag will bind and show only if condition true

<!-- ko foreach: people -->
<span data-bind="text:name"></span>
<!-- /ko -->

<script>
var ViewModel = function () {
this.people = ko.observableArray([
{name:'Tom',age:'24'},{name:'Jerry',age:'30'},{name:'John',age:'29'}
]);
};

ko.applyBindings(); 
</script>
              

Form Fields Bindings

Bindings used in forms.
Click Binding
Like on click event in js. In this example, the count of the click will bind

<span data-bind="text: numberOfClicks"></span>
<button data-bind="click: incrementClickCounter">Click</button>

<script>
var viewModel = {
numberOfClicks: ko.observable(),
incrementClickCounter: function(data,event) {
var previousCount = this.numberOfClicks();
this.numberOfClicks(previousCount + 1);
}
};

ko.applyBindings(); 
</script>
              
Submit Binding
Like on submit event and prevent.default() in js. Helps to avoid accidental submit actions.
Enable Binding
Form field input and button enable or disable. In this example, the count of the click will bind

<input data-bind=enable: {active: firstName()!=""', value: firstName}'></span>

<script>
var ViewModel = {
this.firstName : ko.observable('Tom');
}

ko.applyBindings(); 
</script>
              
Value Binding
Bind value to fields. In this example, the input value will bind if property is not empty.

<input data-bind=enable: {active: firstName()!=""', value:firstName}'>

<script>
var ViewModel = {
this.firstName : ko.observable('Tom');
}

ko.applyBindings(); 
</script>
              
Checked Binding
Bind checkbox checked true/ false. In this example, the checkbox with check if 'checkedStatus' return true.

<input type="checkbox" data-bind='checked: checkedStatus'>

<script>
var ViewModel = {
this.checkedStatus : ko.observable(true);
}

ko.applyBindings(); 
</script>
              
SelectedOptions Binding
In multy-select observe the selected values. In this example, 'selectedNames' will be the selected vaues array.

<select size='5' multiple='true' data-bind='options: names,selectedOption:selectedNames'></select>

<script>
var ViewModel = function () {
this.names = ko.observableArray(['Tom', 'Jerry', 'John', 'Nik', 'Aby', 'Sani', 'Geo']);
this.selectedNames = ko.observableArray();
};

ko.applyBindings(); 
</script>
              

Hope we can share a breaf idea on this topic. If you have any suggestions or questions, please reach us by leave your comment below. thank you...

Author Images
Vishnu Rajeev

Magento Developer - OpsinTech Innovations

Leave Your Comment Here

Latest Post

Adobe Commerce: Explained
  • 21 Jan, 2023
NoSQL Databases: Explained
  • 20 Nov, 2022

Categories

Get a Service From OpsinTech

We're here to serve you. Welcome to our SAAS products and other services.

Start Now

Get a Quote for Your Requirement from Opsin Tech

Get a Quote
  • shape
  • shape
  • shape
  • shape