Table of content

Magento 2 Certified Professional JavaScript Developer Guide


Section 3: Magento Core JavaScript Library

3.1 Demonstrate understanding of the mage library

Describe different types of Magento JavaScript templates

Magento supports the following templates:

  1. Underscore
  2. Knockout
  3. ES6 template
Magento pseudo ES6 literals and underscore templates in Magento

Magento supports ES6 templates. If the browser does not support them, then rendering is performed by the underscore patterns.

ES6 template literals are enclosed by the back-tick (“) character instead of double quotes. But in the Magento template, it is necessary to transfer the pattern enclosed by double or single quotes. Therefore, Magento will automatically apply back-tick if the browser supports ES6 templates.

Describe how to use storage and cookies for JavaScript modules

jQuery Storage API is a plugin that simplifies access to storages (HTML5), cookies, and namespace storage functionality; apart from this, it also facilitates compatibility for old browsers.

To work with jQuery Storage API, connect the jquery and jquery/jquery-storageapi with RequireJS.

The library contains 3 storages:

  1. $.localStorage
  2. $.sessionStorage
  3. $.cookieStorage

Each storage includes the following methods:

  1. storage.get – get an item from a storage
  2. storage.set – set an item in a storage
  3. storage.keys – get keys of a storage or an item in a storage
  4. storage.isEmpty – check if a storage or an item in a storage is empty
  5. storage.isSet – check if an item exists in a storage (if not null or undefined)
  6. storage.remove – delete an item from a storage
  7. storage.removeAll – truncate the storage

$.cookieStorage includes the following additional methods:

  1. $.cookieStorage.setExpires – set expires date in days
  2. $.cookieStorage.setPath – sets path for cookies
  3. $.cookieStorage.setDomain – set domain for cookies
  4. $.cookieStorage.setConf – set cookie configuration with an object
  5. $.cookieStorage.setDefaultConf – sets default configuration
How do you use cookies in the module?

To use cookies in the module, connect jQuery Storage API and call the following methods:

$.cookieStorage.get(‘test_key’);

$.cookieStorage.set(‘test_key’, ‘test_value’);

How is localStorage used in Magento?

In localStorage, there are objects with such keys as mage-cache-storage, mage-translation-storage, product_data_storage, recently_viewed_product, etc. Magento initializes them the following way:

storage = $ .initNamespaceStorage ('mage-cache-storage'). localStorage;

Afterward, Magento uses storage as $ .localStorage.

Demonstrate the ability to use the JavaScript translation framework

How are CSV translations exported to be available in JavaScript modules?

There are two JS file translation strategies: embedded (js files are translated while publishing) and dictionary (dictionary is generated for dynamic translation).

Embedded:

At the deploy, the contents of JS files are translated into the current locale.

Dictionary:

  1. $ .InitNamespaceStorage (‘mage-translation-storage’); is initialized;
  2. $ .InitNamespaceStorage (‘mage-translation-file-version’) is initialized;

If $ .localStorage.get (‘mage-translation-file-version’) is not equal to the current one, then:

  1. Js-translation.json is loaded via RequireJS
  2. The contents of the file are added to the translation database ($ .mage.translate)
  3. The contents of the file are saved in localStorage under the mage-translation-storage name or key
  4. The current version of mage-translation-file-version is saved in localStorage

Otherwise

  1. The contents of mage-translation-storage in localStorage is added to the translation database ($ .mage.translate)
How is a new translation phrase added using JavaScript methods?

In order to add a new translation phrase with JavaScript methods, use jquery and mage / translate into RequireJS and execute $.mage.__(‘My text’).

If the line uses an argument, then execute the following line $.mage.__(‘Hello %1’).replace(‘%1’, yourVariable)

Describe the capabilities of the JavaScript framework utils components

mage/utils (lib/web/mage/utils/main.js) adds methods for Underscore.js.

What are the different components available through the mage/utils module?

The additional methods from mage/utils for Underscore.js:

  1. arrays
    1. toggle – Facade method to remove/add value from/to array without creating a new instance
    2. remove – Removes the incoming value from array in case without creating a new instance of it
    3. add – Adds the incoming value to array if it’s not already present in there
    4. insert – Inserts specified item into container at a specified position
    5. formatOffset
  2. compare
    1. equalArrays – Checks if all of the provided arrays contain equal values
    2. compare
  3. misc
    1. uniqueid – Generates a unique identifier
    2. limit – Limits function call
    3. normalizeDate – Converts mage date format to a moment.js format
    4. inRange – Puts provided value in range of min and max parameters
    5. submit – Serializes and sends data via POST request
    6. ajaxSubmit – Serializes and sends data via AJAX POST request
    7. prepareFormData – Creates FormData object and append this data
    8. filterFormData – Filters data object. Finds properties with suffixand sets their values to properties with the same name without suffix
    9. convertToMomentFormat – Converts PHP IntlFormatter format to moment format
    10. getUrlParameters – Get Url Parameters
  4. objects
    1. nested – Retrieves or defines objects’ property by a composite path
    2. nestedRemove – Removes nested property from an object
    3. flatten – Flattens objects’ nested properties
    4. unflatten – Opposite operation of the ‘flatten’ method
    5. serialize – Same operation as ‘flatten’ method, but returns objects’ keys wrapped in ‘[]’
    6. extend – Performs deep extend of specified objects
    7. copy – Performs a deep clone of a specified object
    8. hardCopy – Performs a deep clone of a specified object. Doesn’t save links to original object
    9. omit – Removes specified nested properties from the target object
    10. isObject – Checks if provided value is a plain object
    11. isPrimitive
    12. forEachRecursive – Iterates over obj props/array elems recursively, applying action to each one
    13. mapRecursive – Maps obj props/array elems recursively
    14. removeEmptyValues – Removes empty(in common sense) obj props/array elems
    15. isEmptyObj – Checks that argument of any type is empty in common sense: empty string, string with spaces only, object without own props, empty array, null or undefined
  5. strings
    1. castString – Attempts to convert string to one of the primitive values, or to parse it as a valid json object
    2. stringToArray – Splits string by separator if it’s possible, otherwise returns the incoming value
    3. serializeName – Converts the incoming string which consists of a specified delimiters into a format commonly used in form elements
    4. isEmpty – Checks whether the incoming value is empty, e.g. ‘null’ or ‘undefined’
    5. fullPath – Adds ‘prefix’ to the ‘part’ value if it was provided
    6. getPart – Splits incoming string and returns its’ part specified by offset
    7. camelCaseToMinus – Converts nameThroughCamelCase to name-through-minus
    8. minusToCamelCase – Converts name-through-minus to nameThroughCamelCase
  6. template
    1. template – Applies provided data to the template

Demonstrate the ability to use and customize the validation module

In order to enable form validation, add the data-mage-init = ‘{“validation” attribute to it: {}}’ attribute to it.

Ways to add fields to the validation:

  1. Add data-validate attribute
  2. Add rule name as an attribute
  3. Add rule name as a class
  4. Add validation inside the data-mage-init attribute of the form tag
How can a custom validation rule be added?

To add a custom validation rule, create a js file and connect it to the page. It is possible to use mixin for connection.

Example:

define(
    [
        'jquery',
        'mage/translate',
        'jquery/validate'
    ], function ($) {
    	$.validator.addMethod('my-test', function(){
    		return true;
    	}, $.mage.__('My test validation error message'));
    }
);

Some forms may use Magento_Ui/js/lib/validation/validator instead of jquery / validate. To add a method into it, call the following method: validator.addRule (name, testFunction, errorMessage);

How can an existing rule be customized?

The existing rule is customized the same way as adding a new rule; the only difference is that it is added with the same name as the rule that needs to be rewritten.

3.2 Demonstrate understanding of mage widgets

Which collapsible widgets are available in Magento? How do you use them?

Accordion widget

The widget is applied to display a single part of the content.

Call: $("#element").accordion();

The #element element must contain child elements together with data-role=”title”

and data-role=”content” attributes

The full list of parameters can be found here: https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_accordion.html

Collapsible widget

Turns the content element into an accordion, in which the content is expanded or collapsed then the header is clicked. Unlike the accordion widget, it is called for a single title/content pair.

Call: $("#element").collapsible();

The full list of parameters can be found here: https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_collapsible.html

Tabs widget

Allows to display a single area with several tabs. Based on the collapsible widget.

Call: $("#element").tabs();

The full list of parameters can be found here: https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_tabs.html

How do you create a new popup, dialog, or modal with the Magento components?

Alert widget

This is a modal window with a single confirmation button.

Call:

$('#element).alert({
    title: 'Warning',
    content: 'Warning content',
    actions: {
        always: function(){} //callback
    }
});

The full list of parameters can be found here:
https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_alert.html

Confirm widget

This is a modal window with confirmation and cancel buttons.

Call:

$('#confirm_element').confirm({
    title: 'Confirmation title',
    actions: {
        confirm: function(){}, //callback when confirmation
        cancel: function(){}, //callback when cancellation
        always: function(){} //is executed each time regardless of the performed action 
    }
});

The full list of parameters can be found here:
https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_confirm.html

Modal widget

This is a configurable modal window with an overlay.

Call: $('#modal_content').modal({});

The full list of parameters can be found here:
https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_modal.html

Prompt widget

This is a modal window with an entry field and confirmation/cancel buttons. This widget is based on the modal widget.

Call:

$('#prompt_element').prompt({
    title: 'Prompt title',
    actions: {
        confirm: function(){}, //callback in case of confirmation
        cancel: function(){}, //callback in case of cancellation
        always: function(){} //performed every time, regardless of taken action
    }
});

The full list of parameters can be found here:
https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_prompt.html

Which other widgets are available in the Magento JavaScript library? How do you use them?

Calendar widget

This is a calendar/date selection widget, based on jQuery Datepicker widget. It can be used in both popup window or in-line. In addition to this, the widget takes into account time zones.

The full list of parameters can be found here:
https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_calendar.html

Gallery widget

This is an adaptive picture gallery with a picture preview feature, based on Fotorama widget.

Call:

<script type="text/x-magento-init">
    {
        "ELEMENT_SELECTOR": {
            "mage/gallery/gallery": {
                "data": [{
                    "thumb": "<small_image_url>",
                    "img": "<small_image_url>",
                    "full": "<small_image_url>",
                    "caption": "<message>",
                    "position": "<number>",
                    "isMain": "<true/false>"
                }]
            }
        }
    }
</script>

The full list of parameters can be found here:
https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_gallery.html

Loader widget

The widget blocks the page, partially or completely, during the ajax queries load.

The full list of parameters can be found here:
https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_loader.html

Menu widget

This is the main menu widget, based on jQuery UI Menu widget.

The full list of parameters can be found here:
https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_menu.html

QuickSearch widget

This is a widget for a quick search popup window.

The full list of parameters can be found here:
https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_quickSearch.html

3.3 Demonstrate the ability to use the customer-data module

Demonstrate understanding of the customer-data module concept

The customer-data module (Magento_Customer / js / customer-data) enables developers to receive the latest actual data for the current user (private data) from the server. The data is loaded with one Ajax request for all requested sections at once.

In order to create a personal data section, one needs to create a class that implements the interface Magento \ Customer \ CustomerData \ SectionSourceInterface and which returns private data for this section, and add the similar code in di.xml:

<type name="Magento\Customer\CustomerData\SectionPoolInterface">
    <arguments>
        <argument name="sectionSourceMap" xsi:type="array">
            <item name="SECTION_NAME" xsi:type="string">SECTION_CLASS</item>
        </argument>
    </arguments>
</type>
What is private data?

Private data is the information that applies to a certain user. Under this category fall such data, as messages, cart, customer, etc. Magento allows to create custom data type, called section.

Why do we need to store information in the browser?

Storing information in the browser is a great way to speed up the process of website loading, because the information is not loaded from the server.

What are performance considerations?

The data is loaded from cookie and localStorage; this process is very fast. Server synchronization of cookies and localStorage is executed in the background.

Demonstrate understanding of how to use the customer-data module in customizations

How is the customer-data module structured?

Customer-data module adds event listeners to all requests and executes Invalidate, when the request is post, put or delete type:

$(document).on('ajaxComplete', function (event, xhr, settings) {
    if (settings.type.match(/post|put|delete/i)) {
        // Invalidate affected sections
    }
});
$(document).on('submit', function (event) {
    if (event.target.method.match(/post|put|delete/i)) {
        // Invalidate affected sections
    }
});

In case the module detects that one or several sections are invalidated, it makes a request to the server and loads the latest data for the corresponding sections.

How is data accessed, invalidated, or set?

GET – run customerData.get(sectionName). Returns knockout observable.

Example: this.cart = customerData.get('cart');

INVALIDATE – run customerData.invalidate(sectionNames) or make post/put/delete request

Example: customerData.invalidate(['cart']);

SET – run customerData.set(sectionName, data)

Example: customerData.set('messages', {});

Describe how to use sections.xml to modify the information available through the customer-data module

Sections.xml is used to make invalidate solely for altered sections after the execution of every post, put or delete requests. This way, you omit the repeated requests in every section.

Below is an example of the sections.xml file. The file is assigned to the action the names of the sections that need to be invalidated if this path is requested via post, put, or delete.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="wishlist/index/cart">
        <section name="wishlist"/>
        <section name="cart"/>
    </action>
</config>
How can a sections.xml file be used to add a new section and to modify the invalidation rules of an existing section?

To add invalidation rules, first create an action tag in sections.xml with the name action that is equal to the path of the server request. If this path is requested via post, put or delete, then the sections connected with this path will automatically invalidate.

The process of changing is similar to adding, only you need to add an action with the same name.

How can a customization change the way existing sections work?

If customization changes the server request path (for example, adding the product to cart), then the standard Magento settings in sections.xml will not work. You will need to re-create these standard rules for the new path

PM Dubina Banner
Andrey-Dubina

Let’s connect

Have a project? Fill out the form and we’ll reach out to you. Get a free proposal now.

Get started