In “Javascript framework RequireJS in magento2” topic we will discuss how RequireJS has been used in magento2. It is the one of javascript framework that has been used in magento2
We will cover

  1. Required JS configuration
  2. javascript modules
  3. javascript execution

 

 

1: Required JS configuration

  • All new js modules must be registered into requirejs-config file
  • The file is located in view/<area>/folder of the modules
  • uses standard requirejs-config js syntax

Example:
This is an example that I took from magento/catalog modules

var config = {
    map: {
        '*': {
            compareItems:           'Magento_Catalog/js/compare',
            compareList:            'Magento_Catalog/js/list',
            relatedProducts:        'Magento_Catalog/js/related-products',
            upsellProducts:         'Magento_Catalog/js/upsell-products',
            productListToolbarForm: 'Magento_Catalog/js/product/list/toolbar',
            catalogGallery:         'Magento_Catalog/js/gallery',
            priceBox:               'Magento_Catalog/js/price-box',
            priceOptionDate:        'Magento_Catalog/js/price-option-date',
            priceOptionFile:        'Magento_Catalog/js/price-option-file',
            priceOptions:           'Magento_Catalog/js/price-options',
            priceUtils:             'Magento_Catalog/js/price-utils',
            catalogAddToCart:       'Magento_Catalog/js/catalog-add-to-cart'
        }
    }
};

any developer should fellow the above basic structure to add new modules. Each modules should be declared as Name. This Name will be used for javascript modules communication and execution.
Example.
compareItems: ‘Magento_Catalog/js/compare’,

  • Name : compareItems
  • The JS path: ‘Magento_Catalog/js/compare’

here we can see three parts depending upon forward slash.

  • Magento_Catalog => Magento/Catalog
  • js => view/<area>/web/js (view/frontend/web/js)
  • compare => compare.js

Final path : compareItems is Magento/Catalog/view/frontend/web/js/compare.js

2: javascript modules

js module generally located in view/<area>/web/jsfolder
There are three types of JS module

  • There are three types of JS module
  • plain module
  • jquery widget
  • UiComponet

1: plain module

A custom JS file that follow AMD rule, else it does not have any specific pre-defined structure

define([
		'jquery',
		'Magento_Customer/js/model/authentication-popup',
		'Magento_Customer/js/customer-data'
	],
	function ($, authenticationPopup, customerData) {
		'use strict';

		return function (config, element) {
			$(element).click(function (event) {
				var cart = customerData.get('cart'),
					customer = customerData.get('customer');

				event.preventDefault();

				if (!customer().firstname && cart().isGuestCheckoutAllowed === false) {
					authenticationPopup.showModal();

					return false;
				}
				location.href = config.checkoutUrl;
			});

		};
	}
);

 

In this above example there are two major parts: a: define the dependency,b: return the statement. On this way magento2 usually return a function with two parameters : config, element

2: jquery widget

It has specific structure to follow AMD rule

define([
		"jquery",
		"jquery/ui"
	], function($){
		"use strict";
		
		$.widget('mage.discountCode', {
			options: {
			},
			_create: function () {
				this.couponCode = $(this.options.couponCodeSelector);
				this.removeCoupon = $(this.options.removeCouponSelector);

				$(this.options.applyButton).on('click', $.proxy(function () {
					this.couponCode.attr('data-validate', '{required:true}');
					this.removeCoupon.attr('value', '0');
					$(this.element).validation().submit();
				}, this));

				$(this.options.cancelButton).on('click', $.proxy(function () {
					this.couponCode.removeAttr('data-validate');
					this.removeCoupon.attr('value', '1');
					this.element.submit();
				}, this));
			}
		});

		return $.mage.discountCode;
	}
);

it has the same define statement and return part is slightly different . uses config, element as parameters and they are hidden inside its structure. here it create(Extent from existing) a jquery widget by passing an object with parameters and functions into $.widget() function.

3: UiComponet

This is new invention by magento2. We will cover this section in UiComponet in magento2

We will take a little look for execution of all those javascript module. There are three different way for executing javascript in magento2

  • Regular requirejs process with a “require” function.
  • Special data-mage-init attribute of a specific DOM element.
  • x-magento-init for multiple element instead of specific DOM element

1: Regular require() call

require([
	"jquery",
	"Magento_Ui/js/modal/modal"
], function($){
	if (this.modal) {
		this.modal.html($('[data-role="system_messages_list"]').html());
	} else {
		this.modal = $('[data-role="system_messages_list"]').modal({
			modalClass: 'modal-system-messages ui-popup-message',
			type: 'popup',
			buttons: []
		});
	}
	this.modal.modal('openModal');
});

In above example , it called require function with two parameters a: list of dependencies, b: function that has those dependencies as parameter.

2: data-mage-init attribute:

  • it allows a json config which will pass to a module (config parameter in module)
  • it execute a module in context of a specific DOM element (element parameter)

e.g: you have a module which do somethings with an DOM element, lets say <div> , the data-mage-init attribute will set its value to json object which lists js modules and configuration for them. That configuration will pass as config parameter to the plain js module.

<div
data-mage-init='{"toolbarEntry": {}}'
class="notifications-wrapper admin__action-dropdown-wrap"
data-notification-count="<?php /* @escapeNotVerified */ echo $notificationCount; ?>">
<?php if ($notificationCount > 0) : ?>
  • It list all module (“toolbarEntry“)
  • config for each module ({})).

3: x-magento-init

it allows the execution of a js module without connecting to a specific DOM-node or multiple node.

<script type="text/x-magento-init">
	{
		".product-add-form": {
			"slide": {
				"slideSpeed": 1500,
				"slideSelector": "#bundle-slide",
				"slideBackSelector": ".action.customization.back",
				"bundleProductSelector": "#bundleProduct",
				"bundleOptionsContainer": ".product-add-form"
				<?php if ($block->isStartCustomization()): ?>
				,"autostart": true
				<?php endif;?>
			}
		}
	}
</script>

above example execute slide functionality on every DOM element that matches a selector “.product-add-form“.

<script type="text/x-magento-init">
	{
		"*": {
			"Magento_Catalog/catalog/category/assign-products": {
				"selectedProducts": <?php /* @escapeNotVerified */ echo $block->getProductsJson(); ?>,
				"gridJsObjectName": <?php /* @escapeNotVerified */ echo '"' . $gridJsObjectName . '"' ?: '{}'; ?>
			}
		}
	}
</script>

In above example it execute “Magento_Catalog/catalog/category/assign-products” js module without connecting to specific DOM element.

 

Hope you understood little bit of the topic “Javascript framework RequireJS in magento2“. Thanks for visit.

 

Check For sample module from GIT

Check For sample module from GIT for “x-magento-init” attribute

 

 

Javascript framework Require JS in magento2
Tagged on:         

Leave a Reply

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