How to use knockout in a simple component in Magento 2

How to use knockout in a simple component in Magento 2
()

Hey fellows, today we will discuss how we can create a simple component and use knockout with it in Magento 2. For simplicity we will create it at home page or CMS index page.

Inside your module create `cms_index_index.xml` layout file and specify a custom block under `content` container.

Know/Module/view/frontend/layout/cms_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="custom.component"
                   template="Know_Module::custom_component.phtml" />
        </referenceContainer>
    </body>
</page>

Now create the custom_component.phtml template file.

Know/Module/view/frontend/templates/custom_component.phtml

<?php
/**
 * @var \Magento\Framework\View\Element\Template $block
 */
?>
<div id="custom-component" data-bind="scope: 'custom-tutorial'">
    <!-- ko template: getTemplate() --><!-- /ko -->
</div>
<script type="text/x-magento-init">
{
    "#custom-component": {
        "Magento_Ui/js/core/app": {
            "components": {
                "custom-tutorial": {
                    "component": "Know_Module/js/customViewModel",
                    "template": "Know_Module/custom-component-tpl"
                }
            }
        }
    }
}
</script>
The <script type=”text/x-magento-init”> method allows to run RequireJS module as a program. It will pass the JSON object into the RequireJS located in the Magento_Ui/js/core/app module.

The component applies to any DOM selector if `*` is specified. However here it will be only applied to the DOM element with id `custom-component`.

The attribute data-bind=”scope: ‘custom-tutorial'” invokes Magento’s Knockout.js scope binding. The scope binding takes a single argument `custom-tutorial`.

Then Magento uses this argument to lookup a view model in uiRegistry and makes this view model the current knockout.js view model for every inner node. The scope data binding can allow different knockout.js view models used on different parts of the page.

Inside div element we have added a “tag-less” Kockout.js binding: <!– ko template: getTemplate() –><!– /ko –>. This binding will render the current view model’s template.

Now it is time to create our custom component js file. So go ahead and create customViewModel.js

Know/Module/view/frontend/web/js/customViewModel.js

define(['uiComponent'], function (Component) {
    "use strict";

    return Component.extend({
        initialize: function () {
            this._super();
            alert("initialized the custom component.");
        }
    });
});

Inside customViewModel.js we’ve extended the `uiComponent`. Whereas the `uiComponent` is an alias of Magento_Ui/js/lib/core/collection component.

Next create the component template file custom-component-tpl.html

Know/Module/view/frontend/web/template/custom-component-tpl.html

<h1>Custom template</h1>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>

Clear the static content and flush the cache, then try it in your browser. At first an alert message will appear:

initialized component alert message

After clicking the “ok” button the template will render.

component rendered template output

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

1 Comment

  • Nice Tutorials !! easily understood.

Leave a Reply

Your email address will not be published. Required fields are marked *