Back to Top

How to extend jQuery widget in magento 2

Updated 28 February 2024

How to extend jQuery widget in magento 2: In this blog we will see how we can extend magento jQuery widget. We can extend jQuery widgets by using mixins.

In java script mixin is a class whose methods are added to, or mixed in, with another class.

In order to extend jQuery widget first we need to declare a mixin in requirejs-config.js file like below.

var config = {
    config: {
        mixins: {
            'Vendor_ParentModule/js/super': {
                'Vendor_ChildModule/js/child': true
            }
        }
    }
};

Now for example parent widget(Vendor_ParentModule/js/super) is like below

define([
    "jquery",
], function ($) {
    "use strict";
    $.widget("mage.customWidget", {
        _create: function() {
            this.foo();
        },
        foo: function() {
            console.log("super class");
        }
    });
    return $.mage.customWidget;
});

Then in child widget(Vendor_ChildModule/js/child) we can override it’s method like below

Searching for an experienced
Magento 2 Company ?
Find out More
define([
    'jquery'
], function ($) {
    'use strict';
    var widgetMixin = {
        foo: function() {
            console.log("do your stuff...");

            return this._super(); // parent method will be called by _super()
        }
    };
    return function (parentWidget) {
        $.widget('mage.customWidget', parentWidget, widgetMixin);
        return $.mage.customWidget;
    };
});

In this way we can override all the methods of jQuery widget in Magento 2. If you have any query then comment below.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home