How to call a function on change of window.checkoutConfig data so to refresh the content of checkout page Magento 2

2.8k views Asked by At

In my checkout page when promo code is applied, I am updating a text using some calculation in knockoutjs

So, I am using window.checkoutConfig data in my js for some calculation. the function works well when called from HTML, but it doesn't run on itself when window.checkoutConfig data is changed, I need to reload the page to see my changes. And this is what knockoutjs is for, Automatic UI Refresh.

Magento_Checkout/web/template/summary/item/details.html

 <span class="tag-text">
    <!-- ko if: getFinalSale($parent)-->
      <u class="product-tag underline-bold-text checkout-final-sale" data-bind="text: getFinalSale($parent)"></u>
    <!-- /ko -->
</span>

I have written above code in details.html

and my js is

Magento_Checkout/web/js/view/summary/item/details.js

knockout js

  define([
   'uiComponent',
   'ko',
   'Magento_Checkout/js/model/totals'
    ], function (Component, ko, totals) {
   'use strict';
    var finalSaleData = window.checkoutConfig.items;

    return Component.extend({
     defaults: {
         template: 'Magento_Checkout/summary/item/details'
     },
    quoteItemData: quoteItemData,
    finalSaleData: finalSaleData,

    /**
     * @param {Object} quoteItem
     * @return {String}
     */

    getItems: function(item_id) {
        var itemElement = null;
        _.each(this.finalSaleData, function(element, index) {
            if (element.item_id == item_id) {
                itemElement = element;
            }
        });
        return itemElement;
    },
    getFinalSale: function (quoteItem) {
        var item = this.getItems(quoteItem.item_id);
        var tagText = '';

        if((((item.price*item.qty) - item.discount_amount)/(item.base_old_price*item.qty))< 0.5){
            var tagText = 'Final Sale';
        }else{
            if(item.base_old_price && item.price){
                // && item.price < item.price && item.base_old_price / item.price <= 0.5){
                if(((item.base_old_price - item.price)/item.base_old_price)>0.5){
                    var tagText = 'Final Sale';
                }
            }
        }
        return tagText;
    },   
  });
});

I am using var finalSaleData = window.checkoutConfig.items in my function getFinalSale.

How to make getFinalSale function run every time when window.checkoutConfig.items data is changed without refreshing the page.

The problem is, this runs only when the page reloads.

How to make getFinalSale function run every time the user applies promo code without refreshing the page so that my HTML gets updated too.

Basically Final Sale text needs to be shown on the basis of that logic in js code in getFinalSale function.

How to achieve that.

0

There are 0 answers