Using Knockout JS, we can create great data bound components in our store’s frontend. One of the most common example, where it used is Magento 2 One page checkout, Although it is used in Onepage Checkout, its implementation in it is very complicated.
The goal of this blog is to explain How to use Knockout JS in Magento 2?
Before we start, if you are not familiar with the knockout JS, then I recommend you to get some basic knowledge about Knockout JS from its official documentation. The documentation link is given below:
First, see the folder structure of the module and download sample module.
In this example all the file are located in ESPL_Knockout module. we'll create the View-Model in grid.js, Located at: app/code/ESPL/Knockout/view/frontend/web/js/view/grid.js
View-Model has dependency 'uiComponent'(Magento_Ui/js/lib/core/collection.js), jquery. ko and it implemented the logic of the knockout js.
View-Model must populate some html content or View. For this purpose we created very simple View in phtml file grid.phtml, Located at: /app/code/ESPL/Knockout/view/frontend/templates/grid.phtml
Now take a closer look at the above defined code.
Magento 2 Initialize Js components by:
When it initialize the component, it Look for the Component id(Which in this case is block-sample-grid)
Next you can see the data-bind Element (data-bind="scope:'sample-grids'"). Its shows that all the the components that initialized will load within this scope. you can find the key sample-grids with the same name within the layout file knockout_index_index.xml, Located at :
In this example we used Knockout template file grid.html, Located at:
After activating Knockout your view should display like below:
One of the big key Advantage of using Knockout JS is that KO updates your content automatically when View-Model is changed. In order to make automatically update content. To Implement, your View-Model class must declare property as observable.
We will demonstrate observable logic with “this.seats” property in our View-Model. We will periodically update property and View should be updated. The best explanation is the working example. Let’s go.
Here we declare the seats, names and availableMeals as the observableArray. So the KO Observer continually observer the all and if any data update the result will directly modified on front view.
We've explained by creating a simple module for you. You can download it from here.
Thanks For Reading!