Category Archive frontend

Enhancing Magento 2 JavaScript Modules with Mixins: A Guide

Introduction:

Magento 2 provides a robust and extensible architecture that allows developers to customize and extend functionality easily. One powerful feature for extending JavaScript modules is the use of mixins. In this article, we will explore how to add a mixin to an existing JavaScript module in Magento 2, drawing parallels to the familiar concept of writing PHP plugins for adding specific treatments after, before or around existing functions.

Understanding Mixins in Magento 2:

Mixins in Magento 2 JavaScript development enable developers to add or override methods in existing classes. This approach promotes code reusability and allows for seamless customization without modifying the core codebase. Just as PHP plugins can extend and modify the behavior of existing PHP classes, mixins empower JavaScript developers to enhance the functionality of JavaScript modules in a clean and modular way.

Prerequisites:

Before diving into the mixin implementation, ensure you have a basic understanding of Magento 2 JavaScript development and are familiar with the structure of the module you intend to extend.

Step 1: Create Your Mixin File:

In your custom module, create a JavaScript mixin file. This file should follow the naming convention "vendor/namespace/view/frontend/web/js/mixin-name-mixin.js". This file will contain the code for your mixin.

Let's say my module vendor and namespace is Addeos_MyModule.

And I want to create a mixin for this core file : vendor/magento/module-checkout/view/frontend/web/js/model/shipping-save-processor/default.js

I am going to create this file:
app/code/Addeos/MyModule/view/frontend/web/js/checkout/model/shipping-save-processor/default-mixin.js
I respect the same folder hierachy.

Here is the content of that file:

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

    return function (defaultShippingSaveProcessor) {
        defaultShippingSaveProcessor.saveShippingInformation = wrapper.wrapSuper(
            defaultShippingSaveProcessor.saveShippingInformation,
            function () {
                console.log('here, I can do want I want.');
                return this._super();
            }
        );
        return defaultShippingSaveProcessor;
    };
});

Step 2: Apply the Mixin to the Target Module:

To apply the mixin to the target module, create a requirejs-config.js file in your module's view/frontend directory.

var config = {
    config: {
        mixins: {
            'Magento_Checkout/js/model/shipping-save-processor/default': {
                'Addeos_MyModule/js/checkout/model/shipping-save-processor/default-mixin': true,
            },
        },
    },
};

Conclusion:

Adding a mixin to an existing JavaScript module in Magento 2 is a powerful way to customize functionality without modifying core code. Drawing parallels to PHP plugins, mixins offer a clean and modular approach to extending JavaScript modules, ensuring maintainability and ease of future upgrades. Incorporate this technique into your Magento 2 development toolkit to create flexible and scalable solutions.

Magento 2 : How to add a knockout component

We can add a knockout component to add some javascript behaviour in our pages. This is how to do it step by step.

1 . In the existing template, in which you want to include the knockout component, you first need to declare the component using the declarative notation and using the <script type="text/x-magento-init" /> tag.

This allows you to specify the component, basically the js file and the associated template.

<script type="text/x-magento-init">
    {
        "#demo-component-container": {
            "Magento_Ui/js/core/app": {
               "components": {
                    "demo-ko-component": {
                        "component" : "MyNamespace_MyModule/js/ko-component",
                        "config" : {
                            "template":  "MyNamespace_MyModule/ko-template"
                        }
                    }
                }
            }
        }
    }
</script>

2. In the same template, you then need to declare the container that will receive the component.

<div id="demo-component-container" data-bind="scope: 'demo-ko-component'">
    <!-- ko template: getTemplate() --><!-- /ko -->
</div>

3. You need to create the js component.

It has to be place in app/code/MyNamespace/MyModule/view/frontend/web/js/ko-component.js.

For the purpose of the example, we are simply setting a property inputValue that we will use in the template.

/**
 * @license http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 * @author Didier Berlioz <berliozd@gmail.com>
 * @copyright Copyright (c) 2016 Addeos (http://www.addeos.com)
 */

define(['jquery', 'uiComponent', 'ko'], function ($, Component, ko) {
        'use strict';
        return Component.extend({
            initialize: function () {
                this._super();
                this.inputValue = ko.observable('my input value');
            }
        });
    }
);

4. You need to create the component template.

It will be placed here app/code/Namespace/Module/view/frontend/web/template/ko-template.html .

As said earlier, in the template we will just bind an input tag with the property inputValue set in the js component.

<p>Here is my knockout template.</p>
<input type="text" data-bind="value: inputValue">

And that's all.

Magento 2 : How to add a jquery widget

When you need to add javascript in your magento 2, one solution is to implement a jQuery widget.
It's pretty simple and straight forward.
This is how to do it step by step.

1. In the phtml template, your need to specify the component that will be available for the dom element :

<script type="text/x-magento-init">
{
  “#dom-id": {
    “componentName": {}
  }
}
</script>

Here componentName will be available for #dom-id

2. Then add the require js config
In <namespace>/<module>/view/frontend/requirejs-config.js add :

var config = {
map: {
    '*': {
      componentName: 'Namespace_Module/js/component'
    }
  }
};

Here you specify that the component componentName will map <namespace>/<module>/js/component.
In other words it will map : /app/code/<namespace>/<module>/view/frontend/web/js/component.js

3. Then create the jQuery widget itself :

In /<namespace>/<module>/view/frontend/web/js/component.js
Add the following code :

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

      $.widget('<namespace>.<module>', {
         _create: function () {
            Console.log(‘boo’);
          }
     });
     return $.<namespace>.<module>;
});

And that's it.