How to use ko.observable on change of data and run a js function Magento 2

by summu   Last Updated July 12, 2019 06:09 AM

How can I run a js function on change of data, So I have heard of knockoutjs ko.observable

define([
 'uiComponent',
 'ko',
 'Magento_Checkout/js/model/totals'
], function (Component, ko, totals) {
'use strict';
 var quoteItemData = window.checkoutConfig.quoteItemData;
 var finalSaleData = totals.totals().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;
    },
    initObservable: function () {
        totals.totals.subscribe(function (total) {

        }, this);

        return this;
    }
getFinalSaleObs: ko.observable(this.getFinalSale(quoteItem))
});

});

But my ko.observable and subscribe is not working. I am trying to run getFinalSale function every time the totals.totals data is changed or window.checkoutConfig.totalsData.item data.

How to achieve that.



Related Questions


Updated November 27, 2018 10:09 AM

Updated December 17, 2018 14:09 PM

Updated February 06, 2019 06:09 AM

Updated July 11, 2019 05:09 AM