What is knockout Js ?
Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Using knockout js we can update UI based on the data model. It’s auto update the UI when the data getting update.
Magento use knockout js in many place. Like minicart, checkout, recently view section…etc.
Today we create our custom simple component in knockout js. Using that component we display the simple message.
Let’s use FirstModule. We add new Knockout js component and using that component we will display the simple message.
Creating Js Component
I am creating js component that component have a message property. That message property we update after 5 second.
//file path: MAGENTO_ROOT/app/code/RS/FirstModule/view/frontend/web/js/hello.js
define(['uiComponent', 'ko'], function(Component, ko) {
return Component.extend({
defaults: {
template: 'RS_FirstModule/hello',
},
message: ko.observable("This message comming from knockout js component"),
initialize: function () {
let self = this;
this._super();
setTimeout(function(){
self.message("Message is updated after 5 second");
}, 5000)
}
});
});
Creating component template
This template is represent the UI. We write the frontend UI code in template file. Also we can use the component peroperties in this template.
We use message property in this template file. Using that message property we display message using Js component.
When we update data dynamically then in magento mostly use knockout js. In our example I updated message property value after 5 second.
<!-- file path: MAGENTO_ROOT/app/code/RS/FirstModule/view/frontend/web/template/hello.html -->
<p class="message" data-bind="text: message()"></p>
How to access the Js component in PHTML template
We access our custom js component in message.phtml template which we created in our FirstModule.
<?php
// file path: MAGENTO_ROOT/app/code/RS/FirstModule/view/frontend/templates/message.phtml
/**
* Product list template
*
* @var $block \Magento\Framework\View\Element\Template
* @var \Magento\Framework\Escaper $escaper
*/
?>
<?= $escaper->escapeHtml(__("This is my first Magento 2.x Module")); ?>
<h2><?= $escaper->escapeHtml(__("Knockout Section")); ?></h2>
<div class="knockout-section" data-bind="scope: 'message_ex'">
<!-- ko template: getTemplate() --><!-- /ko -->
</div>
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"message_ex": {
"component": "RS_FirstModule/js/hello"
}
}
}
}
}
</script>
In above example we access the custom component in PHTML template file. In template file created new section for js component. All the js component data is showing on “knockout-section” div.
Output:
That’s all, For creating a custom js component in Magento 2.