How to use Knockout in Magento 2

Posted on 3 November, 2018

What is Knockout JS?

Knockout Js is a javascript library which is used on the frontend to binding core files in Magento 2. The implementation of Knockout Js in a little bit tricky. As we see that, There are lots of trouble to apply Knockout js in Magento 2. As the title mention, we explain that how to implement Knockout Js easily in Magento 2. So, Let's start the journey of Knockout.

Why KnockoutJS used in Magento 2?

  • The best way to interact with Magento front-end to binding with its component.
  • Working in Model-view-view-Model(MVVM) pattern.
  • Observables and dependency tracking.
  • Most useful for Magento 2 checkout page.
  • Working on any server and purely based on JavaScript.
  • Using KO you can change and update any time selection of UI dynamically.

First of all, we will create a custom module in Magento 2. All files of a module will be located in Emipro_KnockoutJs Module. Now, follow the below steps to create a module.

Let's start.

Step 1: First, create Emipro Folderinto/app/code folder and then, create the KnockoutJs folder into the \app\code\Emipro folder. Now, Create a registration.php file in a \app\code\Emipro\KnockoutJs folder and paste the below code.

 
1
2
3
4
5
6
7
8
9
10
11
<?php
/**
 * Copyright © Emipro Technologies Pvt Ltd. All rights reserved.
 */
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Emipro_KnockoutJs',
    __DIR__
);

Step 2: After, create Emipro Folder we need to create a module.xml file in a \app\code\Emipro\KnockoutJs\etc folder and paste the below code. Make sure that your module name and your namespace is equal.

1
2
3
4
5
<?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="Emipro_KnockoutJs" setup_version="1.0.0" active="true">
    </module>
</config>

Step 3: Create a layout file cms_index_index.xml in the following directory \app\code\Emipro\KnockoutJs\view\frontend\layout and paste the below code. It's an example for cms page. You can set this code in any layout file.

1
2
3
4
5
6
7
8
9
<?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="knockout" template="Emipro_KnockoutJs::emipro_knockoutJs.phtml"/>
        </referenceBlock>
    </body>
</page>

Step 4: Let's create an emipro_knockoutJs.phtml template file in the following directory \app\code\Emipro\KnockoutJs\view\frontend\templates and paste the below code.

Magento parses the script contents within the <script type="text/x-magento-init">. First step is, "emipro-ko-example" [your div id] at this ID of the component it will be initialised.

As you can see here, the component is initialized using an emipro-ko-example name where we defined a path of the knockout js file and knockout html file which we want to display in custom phtml file.

Now, some points are explained here which are related to this phtml file. For ex:

=> "component": "Emipro_KnockoutJs/js/kotemplate"
Here, you need to replace your knockout js file at Emipro_KnockoutJs/js/kotemplate as per knockout file path which is available in your {MagentoRoot}/app/code/VendorName/ModuleName/view/frontend/web/js/ folder.

=> "template" : "Emipro_KnockoutJs/kotemplate"
Here, you need to add .html file extension path at Emipro_KnockoutJs/kotemplate, which is available in your {MagentoRoot}/app/code/VendorName/ModuleName/view/frontend/web/template/ folder.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div id="emipro-ko-example" data-bind="scope:'emipro-ko-example'">
    <!-- ko template: getTemplate() --><!-- /ko -->
    <script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
               "components": {
                    "emipro-ko-example": {
                        "component": "Emipro_KnockoutJs/js/kotemplate",
                        "template" : "Emipro_KnockoutJs/kotemplate"
                        }
                    }
                }
            }
    }
    </script>
</div>

Step 5: Let's create a kotemplate.js file which is an actual component file in the following directory \app\code\Emipro\KnockoutJs\view\frontend\web\js and paste the below code.

1
2
3
4
5
6
7
8
9
10
define(['uiComponent'], function(Component) {
        return Component.extend({
            initialize: function () {
                this._super();
            },
            getText: function () {
                return "call the function here..";
            }
        });
});

initialize: this function is used for initializing our component.
UiComponent : Magento_Ui/js/lib/core/collection.js
uiElement : Magento_Ui/js/lib/core/element/element.js

UiComponent inherits class and methods from uiElement.

For extended initialization code of the parent component, we need to use this._super(); in initialize function.

Step 6: Last step is to create an actual template file to show the content of the component. So, Let's create a kotemplate.html template file in the following directory \app\code\Emipro\KnockoutJs\view\frontend\web\template and paste the below code. Make sure that this file should be made with .html extension.

1
2
3
<h2>Emipro Knockout template call here..</h2>
<div class="emipro-knockout-data-bind-example" data-bind="text:getText()"></div>

In above code, data-bind is a standard way of binding knockout js into code.

That's it. Finally, you are done with your first knockout js module.

I hope this Magento technical note helped you to understand how to use knockoutJs in Magento 2. And, yes our next technical note regarding how to use the ko.observable variable in knockout Js will be coming soon. Please do comment below if you have any other questions or doubts regarding this note.

P.S. Do share this note with your team.


Dharmik Ponda , eCommerce Engineer

Magento Technical Notes

About Emipro

Being an emerging leader in IT market since 2011, Emipro Technologies Pvt. Ltd. has been providing a wide range of business solutions in Odoo & Magento. We are pleased to have a large pool of contented customers with our meticulous work in the domain of ERP & e-Commerce. Our customers are companies of all sizes ranging from startups to large enterprises who realize that they need a professional internet solution to generate revenue streams, establish proper communication channels, to achieve desired goals and streamline business operations. [....] Read More

Our writings seems informative ?

Subscribe for our Magento Technical Notes and get more amazing stuff directly to your inbox!

Post Your Review

X

Your Review has been posted

0 Comment(s)