Magento mixin to replace/expand a javascript component

As a developer we are often facing the task to replace or expand the existing Magento functionality of a UI component that is rendered via javascript. Magento best practices recommend using mixins to do so.

Here is a simple example of using a mixin to replace the purchase order payment method title that is rendered in the checkout page. This is an academic example to showcase the use of a mixin (it doesn’t really have any evident practical usage).

First, we need to declare the mixin, i. e, telling magento that the javascript component used to render the purchase order section in the frontend is to be “mixed” with some custom functionality that we will be coding. This is done in a requirejs-config.js file, which should exist in the root of a custom module or theme. In this case we will be putting it in our custom theme, so the full path for this file will be app/design/frontend/<Theme_Vendor>/<Theme_Name>/requirejs-config.js.

# File: app/design/frontend/<Theme_Vendor>/<Theme_Name>/requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_OfflinePayments/js/view/payment/method-renderer/purchaseorder-method': {
                'Magento_OfflinePayments/js/purchaseorder-method-mixin': true
            }
        }
    }
};

In this file we declare a new mixin to the Magento_OfflinePayments/js/view/payment/method-renderer/purchaseorder-method.js javascript component, that is called purchaseorder-method-mixin.js.
This new mixin file can be found in the app/design/frontend/<Theme_Vendor>/<Theme_Name>/Magento_OfflinePayments/web/js folder.
Note that in the requirejs-config.js file we only write Magento_OfflinePayments/js and we do not include the .js extension to the filename. Magento automatically adds the web folder to this path because all frontend files are placing inside that folder.

Now, we need to create the actual javascript file that will contain our mixin with the code to replace/override the existing functionality. In the example below we will add the string “Method: ” to the title that is placed in the admin for the purchase order payment method.

# File: app/design/frontend/<Theme_Vendor>/<Theme_Name>/Magento_OfflinePayments/web/js/purchaseorder-method-mixin.js

define(function () {
    'use strict';

    var mixin = {

        getTitle: function () {
            return 'Method: ' + this.item.title;
        }
    };

    return function (target) {
        return target.extend(mixin);
    };
});

As you can see, we are rewriting the getTitle() function which is called in the frontend template that renders the purchase order payment method. This function concatenated the “Method :” string with the default title, that we can get with this.item.title.

Hope this help you to understand a bit better how to use a mixin and the advantages of this method.

Leave a Reply

Your email address will not be published.