Magento 2.1.1 – How to Rewrite Widget Function with Mixins

javascriptmagento-2.1.1magento2mixins

We have swatch-renderer.js

In this file there are some widgets.

....
    $.widget('mage.SwatchRenderer', {
....

    /**
     * @private
     */
    _init: function () {
        if (this.options.jsonConfig !== '' && this.options.jsonSwatchConfig !== '') {
            this._sortAttributes();
            this._RenderControls();
        } else {
            console.log('SwatchRenderer: No input data received');
        }
    },

    /**
     * @private
     */
    _sortAttributes: function () {
        this.options.jsonConfig.attributes = _.sortBy(this.options.jsonConfig.attributes, function (attribute) {
            return attribute.position;
        });
    },

I'd like to rewrite some of its functions.

What is the proper way how to do it?

Explanations in magento library are not actual anymore, they are linked on classes which are using another approach (I'm speaking about place-order.js / place-order-mixin.js). And described examples doesn't explain somehow how to rewrite widget functions.

Best Answer

requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_Swatches/js/swatch-renderer': {
                'path/to/your/mixin': true
            }
        }
    }
};

path/to/your/mixin.js

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

    return function (widget) {

        $.widget('mage.SwatchRenderer', widget, {
            _Rebuild: function () {
                console.log('Hello from rebuild', arguments);
                return this._super();
            }
        });

        return $.mage.SwatchRenderer;
    }
});
Related Topic