2

I am working on a customization of the checkout page in M2, in particular I am trying to add to the 'discount' section of the page. In this part of the page I need to call a third party javascript library once the html template has loaded.

I have looked into knockout lifecycle events, however they are unavailable, because they are 3.5.0, and KO version in M 2.3.1 is 3.4.2.

Now I am looking into adding a custom binding, and hoping to add the call to the third party lib in the init method.

My code looks roughly like this:

/app/code/Company/Module/view/frontend/web/js/view/payment/discount.js

define([
    'jquery',
    'ko',
    'uiComponent',
    'Magento_Checkout/js/model/quote',
    'Magento_SalesRule/js/action/set-coupon-code',
    'Magento_SalesRule/js/action/cancel-coupon',
    'certificateInfo',
    "setCertificateInfo",
    "cancelCertificateInfo",
    'Magento_Checkout/js/model/error-processor',
    'Magento_SalesRule/js/model/payment/discount-messages',
], function ($, ko, Component, quote, setCouponCodeAction, cancelCouponAction, certificateInfo, setCertificateInfo, cancelCertificateInfo,errorProcessor, messageContainer) {

    ko.bindingHandlers.myBinding = {
        init: function(element, valueAccessor, allBindingsAccessor, data, context) {
            // Call third party lib here
        }
    }
});

/app/code/Company/Module/view/frontend/web/template/payment/discount.html

<p data-bind="myBinding: blah">
  <!-- Markup that needs to have 3rd party call to work... -->
</p>

All that is happening is an error on the page

[ERROR] Failed to load the "Company_Module/js/view/payment/discount" component.

Any idea what I am doing wrong with custom binding, or a different way to achieve my goal?

1

I think custom Knockout bindings for Magento is Your answer.

Usage example:

<div afterRender="function (target, viewModel) {
    console.log('Rendered element:', target);
    console.log('Associated view model:', viewModel);
    console.log(this === viewModel);
}"></div>

Source: https://devdocs.magento.com/guides/v2.3/ui_comp_guide/concepts/knockout-bindings.html

Useful links: https://community.magento.com/t5/Magento-2-x-PWA-Theming-Layout/How-to-call-function-after-rendering-a-knockout-js-template/m-p/58781#M925

  • YES!!!!! I spent over 2 hours messing with that - thank you sir! – quickshiftin May 10 at 1:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.