SimpleMagento - Magento tutorials, tips and discussions with simplicity in mind
  • Magento 2
  • Frontend
  • Dev Talk
  • Checkout
  • UI components
  • Online Marketing
  • eCommerce Talk
  • Magento 2
  • Frontend
  • Dev Talk
  • Checkout
  • UI components
  • Online Marketing
  • eCommerce Talk
SimpleMagento - Magento tutorials, tips and discussions with simplicity in mind
No Result
View All Result
Home Magento 2

How to use Knockout in Magento 2 – Sample 1

by freelancer
April 22, 2022
0 0
Share on FacebookShare on Twitter

Knockout is javascript library which is used on frontend in Magento 2. It implements Model-View-View Model (MVVM) design sample. You can discover Knockout in Magento 2 on nearly each page. The place the place it’s most modern is the checkout page. This is essentially the most sophisticated implementation in Magento 2.

The purpose of this publish is to clarify how to write KO Model-View and View which is legitimate to use in Magento 2.

We will display how to implement quite simple logic and try to clarify the bottom ideas.
If you’re not conversant in Knockout library I counsel that you simply read documentation on url: (*2*).

In our example, all files are positioned in “simplemagento_Js” module. For this example we created our View-Model in file “koexample.js”, positioned at: app/code/simplemagento/Js/view/frontend/web/js/koexample.js.

Example of our View-Model is beneath:

define(['uiComponent'], function(Component) {
 
        return Component.extend({
            initialize: function () {
                this._super();
		this.sayHello = "Hello this is content populated with KO!";
            }
        });
});

Our View-Model has as dependency ‘uiComponent’ (Magento_Ui/js/lib/core/collection.js). UiComponent inherits class and methods from “uiElement” (Magento_Ui/js/lib/core/ingredient/ingredient.js) and over final class our View-Model has implementation of Knockout logic.

If you open “Magento_Ui/js/lib/core/element/element.js” you will discover ko object as dependency in define function from requireJS:

define(['ko', 'underscore', 'mageUtils', 'uiRegistry', 'uiEvents', 'uiClass', './links', '../storage'],
function (ko, _, utils, registry, Events, Class, links) {
    'use strict';
....

View-Model ought to populate some html content or View. For this objective we created quite simple View in phtml file:

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

In our example we used Knockout template file example.html, which accommodates subsequent content (template file is outlined in code above “template” : “simplemagento_Js/example”). Template file is dynamically loaded by javascript.

<p>I am template located on: app/code/simplemagento/Js/view/frontend/web/template/example.html and dynamically loaded. This is my message to you:</p>
<p data-bind="text: sayhello"></p>

After activating Knockout your view ought to show:

<p>I am template located on: app/code/simplemagento/Js/view/frontend/web/template/example.html, dynamically loaded. This is my message to you:</p>
<p data-bind="text: sayhello">Hello this is content populated with KO!</p>

One of the large key advantages of Knockout is that KO updates your content mechanically when View-Model is modified. In order to make mechanically replace content you must in your View-Model class declare property as observable.

We will display observable logic with “this.time” property in our View-Model. We will periodically replace property and View ought to be up to date. The greatest rationalization is on the working example. Let’s go.

define(['uiComponent'], function(Component) {
 
        return Component.extend({
            initialize: function () 
                this._super();
                this.time = Date();
                //time is defined as observable
                this.observe(['time']);
                //periodically updater every second
                setInterval(this.flush.bind(this), 1000);
            ,
            flush: function(){
                this.time(Date());
            }
        });
});

In “initilalize” method we created property “time” and declared as observable with method “this.observe([‘time’])“.

This “observe” method is from class “Magento_Ui/js/lib/core/element/element”. If you need to look at the entire logic, open this file and discover method “observe”.

With javascript function “setInterval” we periodically replace property “time” with new value. It implies that KO ought to automaticaly replace View with new value.

One thing more, you must modify your View (ko template file) and it ought to appear like seen beneath:

<p>I am example3.HTML template, dynamically loaded. This is my message to you:</p>
<p data-bind="text: time"></p>

When you activated Knockout, html/content ought to be up to date each second. Html ought to appear like this:

<div data-bind="scope: 'koexample'">
<!-- ko template: getTemplate() --><p>I am example3.HTML template, dynamically loaded. This is my message to you:</p>
<p data-bind="text: time">Mon Mar 07 2016 12:58:30 GMT+0100 (CET)</p><!-- /ko -->
</div>

Time is up to date each second by Knockout utilizing observable.

I hope that you simply understood this easy example and that it will likely be useful in your development.

In case you’re feeling you want some additional assist, we will offer you a detailed custom report based on our technical audit – be happy to get in contact and see what we will do for you!

Tags: Magento 2FrontendCheckout
Previous Post

Featured products in Magento 2 with Catalog Products List widget – Sample 1

Next Post

Add new console command in Magento 2 – Sample 1

freelancer

freelancer

Related Posts

Magento 2

Implementing payment gateway in Magento 2 – Sample 1

April 22, 2022
Magento 2

Implementing payment gateway in Magento 2 Spinned – Sample 1

April 22, 2022
Magento 2 Payment

Implementing payment gateway in Magento 2 – Sample 1

April 22, 2022
Magento 2

Routing in Magento 2 – Sample 1

April 22, 2022
MVC Magento 2

Magento 2 Controllers – Sample 1

April 22, 2022
Magento 2

How to create a basic module in Magento 2 – Sample 1

April 22, 2022

Leave a Reply Cancel reply

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

Categories

  • Administration
  • Search
  • Configuration
  • Starting Up
  • Extensions
  • News
  • PWA
  • Magento 2 API
  • Programming
  • MVC Magento 2
  • UX/UI Design
  • Shipping Magento 2
  • Database
  • Magento 2 Payment
  • Magento 2
  • Cache
  • Frontend
  • Integration
  • Dev Talk
  • Life at Inchoo
  • Checkout
  • Tips
  • UI components
  • Products
  • Online Marketing
  • Debugging
  • Magento
  • Search Magento 2
  • Upgrading Magento 2
  • Marketing
  • eCommerce Talk
  • Events & Observers
  • Uncategorized

Popular Post

Magento 2

Magento 2 frontend architecture – Sample 1

April 22, 2022
Magento 2

Magento 2 Luma Theme Under The Scope

March 27, 2022
Magento 2 Payment

Implementing payment gateway in Magento 2 – Sample 1

April 22, 2022
Dev Talk

Moving the validation error message, this time globally

March 25, 2022
No Result
View All Result
[vc_row full_width="stretch_row" vc_row_background="" css=".vc_custom_1516082354216{margin-top: 30px !important;padding-top: 22px !important;padding-bottom: 22px !important;}"][vc_column el_class=".footer_center" offset="vc_col-lg-offset-3 vc_col-lg-6"]
[vc_empty_space height="15px"][vc_column_text css=".vc_custom_1516083863519{margin-bottom: 0px !important;}" el_class=".copyright"]Copyright © 2018 JNews. Photography Blog theme by Jegtheme.[/vc_column_text][/vc_column][/vc_row]
No Result
View All Result
  • Magento 2
  • Frontend
  • Dev Talk
  • Checkout
  • UI components
  • Online Marketing
  • eCommerce Talk

© 2023 JNews - Premium WordPress news & magazine theme by Jegtheme.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In