Magento, Magento 2

How to use Knockout JS in Magento 2

How to use Knockout in Magento 2

Welcome back to Rohan’s new blog. In this article, we are learning about what is the use of knockout JS and how to implement in custom module in Magento2. There are big role of knockout js to make Magento 2 more secure and fast. Main purpose of this post is to explain how to use knockout js in custom module very easily. Before, start implement knockout js in custom module let’s go for understand what is knockout js and use of knockout js.

What is Knockout JS?

Knockout js is a one type of javaScript Library which is used to dynamically build some parts of it’s front-end. It implements MVVM (Model-View-View-Model) design pattern. We all know there are little bit tricky structure to implement knockout in Magento2. But, here I will explain in very easy way to implement knockout in Magento 2.

Why Knockout JS used in Magento 2?

Observables and Dependency tracking

Observables means it is useful for update your UI automatically when the view model or content will be change. For that, you need to declare your model properties as Observables. It can notify to subscribers about changes and it will automatically detect dependencies.

Example :

var rhViewModel = {
    personName: ko.observable('Rohan'),
    personAge: ko.observable(10)
};

Dependency tracking is actually working whenever you declare a computed observable. When observable declare, knockout automatically invokes and get its initial value. Whenever that appropriate function will running, knockout will be setup subscription to all observables and looping process till ends and read values and then set new values to computed observables.

Declarative bindings

Declarative binding is one of the best way to interect with Magento 2 UI Component. It’s useful for understand relationship between binding and ko observables.

Let’s start to create simple module for implement knockout in custom module :

MageRoot = /app/code/RH/KnockoutExe

Add this below code in {MageRoot} > registration.php

<?php

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 *
 * Created By : Rohan Hapani
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'RH_KnockoutExe',
    __DIR__ 
);

To setup module version add this below code inside {MageRoot} > etc > module.xml file :

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 *
 * Created By : Rohan Hapani
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
   <module name="RH_KnockoutExe" setup_version="1.0.0" active="true" />
</config>

Create a layout file {MageRoot] > view > frontend > layout > cms_index_index.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 *
 * Created By : Rohan Hapani
 */
-->
<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="RH_KnockoutExe::rh_knockoutExe.phtml" />
      </referenceBlock>
   </body>
</page>

Add template file  {MageRoot} > view > frontend > templates > rh_knockoutExe.phtml

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

Now, Looks little bit closer inside a code.

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

It’s a declarative notation which is parsed to extract component names and configuration will be applied to that element. Here, it will initialise rh-ko-example component.

Now, create component js file {MageRoot} > view > frontend > web > js > rhkojs.js

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

Create an actual template html file for display content of the component inside {MageRoot} > view > frontend > web > template > knockout-test-example.html

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

Clear cache and then run php bin/magento s:s:d -f or php bin/magento s:s:d command for deploy and check it at front side.

I hope this blog is easy to understand about How to use Knockout JS in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution 🙂

Tagged ,