Knockout is a library of JavaScript that helps build responsive and rich display as well as editor user interfaces with an underlying model that’s clean. Anytime there are UI sections that dynamically update, Knockout could help implement it in a maintainable and simple way.
The headline features of the library include:
- Declarative bindings – an obvious and simple way of connecting parts of the UI to the data model. Constructing a dynamic and complex User Interface is easy with the binding contexts that are arbitrarily nested.
- Dependency tracking that’s elegant – updates the right UI parts automatically each time the data model changes.
- Trivially extensible – customer behaviors are implemented as new declarative
Why KnockoutJS is relevant to Magento 2?
In today’s cyber-era, an online presence has become paramount for businesses of all shapes and sizes. Thus, Magento 2 development services are highly in demand. For those who are just starting to learn the Magento platform, or have been doing it for a while, there’s a bigger chance that you haven’t given a deeper thought about Knockout.
Nonetheless, it’s important to understand what KnockoutJS is all about since its data-binding concept has been pretty much used in several important elements of the platform, including checkout and minicart. Knockout makes use of the MVVM pattern for binding data to particular DOM elements.
Big Change in the Magento 2 Frontend
One of the biggest changes introduced to the Magento 2 front-end space is Knockout. Although it was difficult to grasp at the start, it comes out as an extremely useful tool at the end of the day. Truly, the library shines in instances when you need to update something in accordance to the input of users or other actions.
It brings to the table the ‘observable’s, which are variables that could be updated automatically and informs all interested parties that they’ve been changed. Aside from that, there is a ‘computed’ kind of functions fired automatically on update of any observable within it. Adding the number of possibilities that are easy to obtain must be clear now.
Why Data-Binding?
When consulting a Magento 2 development company, you might ask if it’s okay to just use some other library like jQuery to manually parse the DOM. Well, you can of course and won’t even need jQuery. All DOM manipulations could be done, along with JavaScript too.
Libraries such as these however help in writing beautiful, maintainable, and standardized code. Say for instance a page in which the number of visitors are showcased on three separate page sections.
<div class=”visitors”></div>
<!--Some other HTML-->
<div class=”visitors”></div>
<!--Some other HTML-->
<div class=”visitors”></div>
The JavaScript will appear something like this, which, in every second fetches new visitor data.
<script type=”text/javascript”>
(function ($) {
var visitors = 0;
var fetchVisitorurl = “...”;
var fetchVisitors = function () {
$.get(fetchVisitorUrl, function (data) {
visitors = data.visitors;
$(‘.
visitors’).
html(visitors);
setTimeout(fetchVisitors, 1000);
});
}
);
fetchVisitors();
})
(window.jQuery);
</script>
Check out the $(‘.visitors’).html(visitors);. The line is responsible for making the DOM manipulation actually. Even if a new visitor data is fetched, it will not be visible on the page without that line.
Supposing a new developer decides implementing a better way of fetching visitor data on your project? He/She would have to write the line in the code. Thus, code gets redundant and messy. With data-binding the View-Model is the only one changed and automatically the view changes.
Knockout and Magento 2
The first thing to do with in making a knockout Magento 2 app is to create a new module. We write the following on our next template file.
<?php
/* @var Codilar\HelloWorld\Block\Hello $block */
?>
<div data-bind=”scope: ‘knockout-tutorial’>
<!-- ko template: getTemplate() -→<!-- /ko -->
</div>
<script type=”text/x-magento-init”>
{
“*”:{
“Magento_Ui/js/core/app”:{
“components”:{
“knockout - tutorial”:
{
“component”: “Codilar_Helloworld/js/viewmodel”,
“template”: “Codilar_Helloworld/template”
}
}
}
}
}
</script>
This is basically initiating the Magento_Ui/js/core/app widget with the components passed as options, using the text/x-magento-init tag. The data bind=”scope: ‘knockout-tutorial’” says knockout to use the knockout-tutorial component and template inside that DIV.
We write the component file next,
app/code/Codilar/HelloWorld/view/frontend/web/js/viewModel.js
define([
‘uicomponent’,
‘ko’
],
function (component, ko) {
return component.extend9
{
clock: ko.observable(“”)
initialize: function () {
this._super();
setInterval(this.reloadTime.bind(this), 1000);
},
reloadTime: function () {
/*Setting new time to our clock variable. DOM manipulation will happen automatically */
this.clock(Date());
},
getclock: function () {
return this.clock;
}
};
};
The View-Models within the Magento 2 app should return a Component.extend function call in which the object of the uiComponent is the Component, that’s required here. Within the Component.extend, we pass an object that should have an initialize function that would be the ‘class constructor’.
Finally, we build the template file
app/code/Codilar/HelloWorld/view/frontend/web/template/template.html
<!-- My View-Model file is Codilar_HelloWorld/js/viewModel -->
<h1 data-bind=”text: getClock()”></h1>
Upon hitting the http://mywebsite.com/helloworld/ URL, we should see a clock that changes each second, even if we did not do any manipulations to the DOM explicitly.
That is what the bindings of Magento 2 and KnockoutJS is all about.
KnockoutJS Prominent Features
1. Model-View-View Model Framework. Knockout offers an MVVM or the app design architecture.
Model – represents information or data. Stores information, but doesn’t store services or behaviors that manipulate information. It’s performed with the View and View Model help since both are interlinked via binding mechanism that’s two-way.
View – an actual end user data representation. View, an HTML template containing Knockout bindings. It makes use of data-bind attributes for displaying data and editing. It has HTML elements, including images, grids, links, buttons, and many more.
View Model – the View and Model intermediary. It is in KnockoutJS a representation of JavaScript as well as the functions associated for data manipulation.
2. In-Built Templating. Knockout provides templating that’s DOM-based and used HTML as the templating engine by default. However, it supports other templating that are string-based. Templating enables apps to render reusable and modular views. With Knockout, you could do string-based or DOM templating to modularize views as well as render them in a programmed manner.
3. Declarative Binding. Knockout is pretty useful because it enables embedding data binding expressions in the HTML. It enables DOM elements association with model data with a simple syntax. Since it’s a data-binding library, it lets you build custom bindings within the data-bind.
In short, it enables custom behaviors implementation as new declarative bindings for easy reuse with just a few code lines.
4. Two-Way Data Binding. The binding mechanism is between the UI and the data model, meaning that any change performed to the data model would be reflected in the UI automatically and vice versa. An HTML page’s UI elements reflect the changes made to the Data Model through automatic updating of the DOM.
In Conclusion
Most other frameworks of JavaScript bind the whole HTML document. Knockout however binds to a particular DOM obtainer, thus it’s different from the rest. It’s a sturdy tool for DOM manipulations management.