Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

How to Use Mixins in Magento 2

Vinh Jacker | 10-01-2024

How to Use Mixins in Magento 2 How to Use Mixins in Magento 2

The Most Popular Extension Builder for Magento 2

With a big catalog of 224+ extensions for your online store

In Magento 2, mixins play a crucial role in extending or modifying functionality without directly altering core files. They achieve this by injecting custom code into existing classes. While in the back-end, you often use plugins or extensions to enhance functionality or manipulate data, JavaScript mixins offer an alternative approach. In this article, we’ll explore how you can use JavaScript mixins to override component methods.


Reports Extension

Reports for Magento 2

Implement deeper analysis - Make better decisions with effective advanced statistic reports

Check it out!


What is Magento 2 Mixin in JavaScript?

A mixin is a class whose methods are added to, or mixed in with another class. Instead of inheriting from the mixin, the base class includes its methods. This approach allows you to augment the behavior of the base class by inserting different mixins into it.

How to Use Mixins in Magento 2

Mixin scope

The scope of a module’s mixin depends on its directory location under the view directory. This allows you to target component instances in specific areas.

The following table maps a directory location to the application area a mixin affects:

</thead>
DIRECTORY SCOPE
view/frontend Storefront
view/adminhtml Admin panel
view/base All areas (unless a specific frontend or adminhtml entry exists)

Mixin files

Location

Mixins are JavaScript files located under the web/js directory under an area-specific directory. The mixin file can be nested under more directories as long as those directories are under web/js.

Format

A mixin is written as an AMD module that returns a callback function. This function accepts a target component(module) as an argument and returns a module.

This allows you to return a new instance of the target component with your modifications attached to it before it is used in the application.

Examples

Extending UI component

This is a typical example of a mixin. It modifies the target component by adding a blockVisibility property specifically to its column elements.

File: Mageplaza/Customize/view/base/web/js/columns-mixin.js



define(function () {
    'use strict';

    var mixin = {

        /**
         *
         * @param {Column} elem
         */
        isDisabled: function (elem) {
            return elem.blockVisibility || this._super();
        }
    };

    return function (target) { // target == Result that Magento_Ui/.../columns returns.
        return target.extend(mixin); // new result that all other modules receive
    };
});

Extending jQuery widget

The following is an example of a mixin that extends the modal widget with a function that adds confirmation for a modal closing.

File: Mageplaza/Customize/view/base/web/js/modal-widget-mixin.js

define(['jquery'], function ($) {
   'use strict';


   var modalWidgetMixin = {
       options: {
           confirmMessage: "Please, confirm modal closing."
       },


       /**
        * Added confirming for modal closing
        *
        * @returns {Element}
        */
       closeModal: function () {
           if (!confirm(this.options.confirmMessage)) {
               return this.element;
           }


           return this._super();
       }
   };


   return function (targetWidget) {
       // Example how to extend a widget by mixin object
       $.widget('mage.modal', targetWidget, modalWidgetMixin); // the widget alias should be like for the target widget


       return $.mage.modal; //  the widget by parent alias should be returned
   };
});

Extending JS object

Another use-case for the JS mixin is when the base Javascript file returns an object. In this case, a wrapper is necessary. The following example mixin extends the setHash method of step navigator object. Here, this._super() is the base method that can be called if needed. File: Mageplaza/Customize/view/frontend/web/js/model/step-navigator-mixin.js


define([
   'mage/utils/wrapper'
], function (wrapper) {
   'use strict';


   return function (stepNavigator) {
       stepNavigator.setHash = wrapper.wrapSuper(stepNavigator.setHash, function (hash) {
           this._super(hash);
           // add extended functionality here or modify method logic altogether
       });


       return stepNavigator;
   };
});

Declare a mixin

Mixins are declared within the mixins property of the requirejs-config.js configuration file, which should be situated in the same directory as the defined mixin. Furthermore, this configuration file ensures the association of a target component with a mixin via their respective paths.

Example

The following is an classic example of a requirejs-config.js file. It adds the columns-mixin, modal-widget-mixin, step-navigator-mixin, and proceed-to-checkout-mixin mixins, which were defined in the previous examples, to the grid column component, modal widget, step navigator object, and proceed to checkout function.

File: Mageplaza/Customize/view/base/requirejs-config.js

var config = {
config: {
    mixins: {
        'Magento_Ui/js/grid/controls/columns': {
            'Mageplaza_Customize/js/columns-mixin': true
        },
        'Magento_Ui/js/modal/modal': {
            'Mageplaza_Customize/js/modal-widget-mixin': true
        },
        'Magento_Checkout/js/model/step-navigator': {
            'Mageplaza_Customize/js/model/step-navigator-mixin': true
        },
        'Magento_Checkout/js/proceed-to-checkout': {
            'Mageplaza_Customize/js/proceed-to-checkout-mixin': true
        }
    }
}

Overwrite a mixin

A mixin can be overwritten by another mixin but cannot be disabled separately.

Example

File: Mageplaza/CartFix/view/base/requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_Catalog/js/catalog-add-to-cart': {
                'Mageplaza_Customize/js/original-add-to-cart-mixin': false,
                'Mageplaza_CartFix/js/overwritten-add-to-cart-mixin': true
            }
        }
    }
};

In this case, the Mageplaza_Customize/js/original-add-to-cart-mixin is overwritten by Mageplaza_CartFix/js/overwritten-add-to-cart-mixin. Be sure to add the origin module as the over-written module dependency (use the sequence tag in etc/module.xml).

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="'Mageplaza_CartFix">
        <sequence>
            <module name="'Mageplaza_Customize" />
        </sequence>
    </module>
</config>

After making changes to the requirejs-config.js configuration, you must clean the cache and regenerate static files.

Conclusion

Mixins in Magento 2 provide a flexible way to enhance functionality without directly modifying core files. By following the steps above, you can effectively use mixins to customize your storefront behavior. If you encounter any issues, feel free to seek expert guidance from us.

Remember, mixins allow you to extend Magento 2’s capabilities while maintaining a modular and maintainable codebase. Happy coding!

Table of content
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services