How to Use Knockout JS in Magento 2?

 

 

Magento 2, ever since its inception, has undergone lots of changes. But, Knockout JS was one of the biggest changes that were introduced to the Magento 2.

What is Knockout JS?

Knockout JS is basically a type of JavaScript Library that is used for dynamically building certain parts of the Magento 2 frontend.

It uses MVVM (Model-View-View-Model) pattern, which is a bit of a tricky structure to learn and implement in Magento 2. But, it helps to add a great deal of seamless functionality on a Magento 2 based online store.

Plus, Knockout JS also makes the Magento 2 development process quite interesting and extremely powerful.

To put it simply, the data binding concept of Knockout JS is vital and used in many crucial elements of Magento like checkout and mini cart.

Now, at this point, many of you might be thinking…

Why Use Data Binding in the First Place?

“Can’t we use a simple library such as JQuery to perform the DOM parsing manually?”

The answer is - You most certainly can!

In fact, you don’t even have to use JQuery for that. You can easily perform all the DOM manipulations by using the core JavaScript as well. However, Knockout JS can help to write a more standardized, beautiful, and maintainable code in Magento 2.

Plus, it also makes the Magento 2 fast and secure. So in this post, we will explain exactly how to use Knockout JS in Magento 2 and implement it in a custom module.

How to Use Knockout JS in Magento 2?

In order to use Knockout JS in Magento 2, we need to create a simple module to implement the Knockout JS in the custom module.

Let’s get started.

Step #1

Go to > MageRoot = /app/code/MD/KnockoutExe

Step #2

Now, add the below-mentioned code in {MageRoot} > registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'MD_KnockoutExe',
__DIR__
);

Step #3 
Next, we need to set up the module version.
To do that, we need to add the below-mentioned code in the {MageRoot} > etc > module.xml file:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="MD_KnockoutExe" setup_version="1.0.0" active="true">
    </module>
</config>

Step #4 

Now, we need to create a layout file {MageRoot] > view > frontend > layout > cms_index_index.xml</em

<?xml version="1.0" encoding="UTF-8"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="content">
<block class="Magento\Framework\View\Element\Template" name="knockoutexe" template="MD_KnockoutExe::m_knockoutExe.phtml"/>
</referenceBlock>
</body>
</page>

Step #5
Next, we need to add a template file {MageRoot} > view > frontend > templates > md_knockoutExe.phtml

<div id="md-knockout-example" data-bind="scope:'md-ko-example'">
<!-- ko template: getTemplate() --><!-- /ko -->
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"md-ko-example": {
"component": "MD_KnockoutExe/js/mdkojs"
}
}
}
}
}
</script>
</div>

Step #6

Now, let’s look a little bit closer inside a code.

<script type="text/x-magento-init">

It’s basically a declarative notation that is parsed for extracting component names. In addition, the configuration will also be applied to that element.

At this point, it will initialize the md-ko-example component.

Step #7 

The next step is to create a component js file {MageRoot} > view > frontend > web > js > mdkojs.js

define(['jquery', 'uiComponent', 'ko'], function ($, Component, ko) {
'use strict';
return Component.extend({
defaults: {
template: 'MD_KnockoutExe/knockout-test-example'
},
initialize: function () {
this._super();
}
});
}
);

Next, we need to create an actual template HTML file in order to display the content of the component {MageRoot} > view > frontend > web > template > knockout-test-example.html

<div class="component-class">
<div data-bind="text: 'Knockout Works Successfully'"></div>
</div>

Step #8

The process is almost finished. The thing remains now is to clear the cache and then run command to deploy and check it at the front side.

php bin/magento s:s:d -f or php bin/magento s:s:d

Also read: How to Use if Else in Knockout JS in Magento 2?

Conclusion

Knockout JS provides plenty of benefits when used in Magento 2. It not only helps to create rich front-end components, which ultimately enhances the user experience of an online store, but it also makes your online store much faster and secure.

If you have any queries or need our professional assistance with your Magento development agency, feel free to reach out to us anytime.