Edit in GitHubLog an issue

jQuery widget coding standard

All Adobe Commerce and Magento Open Source jQuery UI widgets and interactions are built on a simple, reusable base---the jQuery UI Widget Factory.

The factory provides a flexible base for building complex, stateful plug-ins with a consistent API. It is designed not only for plug-ins that are part of jQuery UI, but for general usage by developers who want to create object-oriented components without reinventing common infrastructure.

For more information, see the jQuery Widget API documentation.

This standard is mandatory for core developers and recommended for third-party extension developers. Some parts of the code might not comply with the standard, but we are working to gradually improve this.

Use RFC 2119 to interpret the "must," "must not," "required," "shall," "shall not," "should," "should not," "recommended," "may," and "optional" keywords.

Naming conventions#

  • Widget names must consist of one or more non-abbreviated English word and in camelcase format.

    Copied to your clipboard
    1(function($) {
    2 $.widget('mage.accordion', $.ui.accordion, {
    3 // ... My custom code ...
    4 });
  • Widget names should be verbose enough to fully describe their purpose and behavior.

    Copied to your clipboard
    1// Declaration of the frontend.advancedEventTrigger widget
    2(function($) {
    3 "use strict";
    4
    5 $.widget('mage.advancedEventTrigger', $.ui.button, {
    6 // ... My custom code ...
    7 });
    8}) (jQuery);

Instantiation and resources#

  • Additional JavaScript files used as a resources must be dynamically loaded using the $.mage.components() method and must not be included in the <head> block.

  • Use the $.mage.components() method to load additional JavaScript resource files not included in the <head> block.

  • You must use $.mage.extend() to extend an existing set of widget resources.

  • You must instantiate widgets using the data-mage-init attribute. You can use the .mage() plug-in to instantiate widgets that use callback methods.

    Benefits:

    • You leverage the benefits of $.mage.extend() and $.mage.components().

    • Using data-mage-init minimizes the inline JavaScript code footprint.

    • You can modify widget initialization parameters.

      Copied to your clipboard
      1// Widget initialization using the data-mage-init attribute
      2<form data-mage-init="{form:[], validation:{ignore:':hidden'}}"></form>
      3
      4// Widget initialization using the mage plug-in
      5(function($) {
      6 $('selector').mage('dialog', {
      7 close: function(e) {
      8 $(this).dialog('destroy');
      9 }
      10 });
      11})(jQuery);
  • You can declare callback methods inline JavaScript but not methods and widgets.

    Copied to your clipboard
    1// Widget initialization and configuration
    2$('selector').mage('dialog', {
    3 close: function(e) {
    4 $(this).dialog('destroy');
    5 }
    6});
    7
    8// Widget initialization and binding event handlers
    9$('selector').mage('dialog').on('dialogclose', {
    10 $(this).dialog('destroy');
    11});
    12
    13// Extension for widget in a JavaScript file
    14$.widget('mage.dialog', $.ui.dialog, {
    15 close: function() {
    16 this.destroy();
    17 }
    18});
    19
    20// Extension of widget resources
    21(function($) {
    22 $.mage
    23 .extend('dialog', 'dialog',
    24 '<?php echo $this->getViewFileUrl('Enterprise_\*Module\*::page/js/dialog.js') ?>')
    25})(jQuery);

Initializing a component on a selector#

There are two ways to initialize a component on a selector:

  • Initialize the component in the data-mage-init attribute:

    Copied to your clipboard
    <div id="element-id" data-mage-init='{"Vendor_Module/js/myfile":{}}'></div>
  • Use a script type text/x-magento-init attribute:

    Copied to your clipboard
    1<script type="text/x-magento-init">
    2{
    3 "#element-id": {
    4 "Vendor_Module/js/myfile": {}
    5 }
    6}
    7</script>

In these cases the path to the file is:

Vendor/Module/view/frontend/web/js/jsfilename.js

which contains your code:

Copied to your clipboard
1define(['uiComponent'],
2 function (Component) {
3 'use strict';
4 return Component.extend({
5 initialize: function (config, node) {
6 // some code
7 }
8 });
9 });

Initializing a component on a selector with parameters#

When a component is initialized, it is also important to send parameters to it, which are normally determined dynamically in PHP.

  • data-mage-init

    Copied to your clipboard
    1<div id="element-id" data-mage-init='{"Vendor_Module/js/myfile":{"parameter":"value","status":<?php echo $block->getStatus(); ?>
    2}}'></div>
  • Using a script type text/x-magento-init attribute. For example:

    Copied to your clipboard
    1<script type="text/x-magento-init">
    2{
    3 "#element-id": {
    4 "Vendor_Module/js/myfile1": {
    5 "parameter":"value",
    6 "status":<?php echo $block->getStatus(); ?>
    7 }
    8 }
    9}
    10</script>

Development standards#

  • Widgets should comply with the single responsibility principle.

    Widgets should not have responsibilities not related to the entity described by the widget.

    Copied to your clipboard
    1// Widget "dialog" that is responsible
    2// only for opening content in an interactive overlay.
    3$.widget('mage.dialog', {
    4 // Code logic
    5});
    6
    7// Widget "validation" that is responsible
    8// only for validating the form fields.
    9$.widget('mage.validation', $.ui.sortable, {
    10 // Code logic
    11});
    12
    13$('selector')
    14 .mage('dialog')
    15 .find('form')
    16 .mage('validation');
  • Widget properties that modify the widget's behavior must be located in the widget's options to make them configurable and reusable.

    Copied to your clipboard
    1//Declaration of the backend.dialog widget
    2$.widget('mage.dialog', {
    3 options: {
    4 modal: false,
    5 autoOpen: true,
    6 // Additional widget options
    7 },
    8 // Additional widget properties
    9});
    10
    11// Initializing
    12$('selector').mage('dialog', {
    13 modal: true,
    14 autoOpen: false
    15});
  • Widget communications must be handled by jQuery events

    Copied to your clipboard
    1<body>
    2 ...
    3 <button data-mage-init="{button: {event: 'save', target:'[data-role=edit-form]'}}" />
    4 ...
    5 <form data-role="edit-form">
    6 ...
    7 </form>
    8 ...
    9</body>
    Copied to your clipboard
    1// Declaration of the mage.form widget
    2$.widget("mage.form," {
    3 _create: function() {
    4 this._bind();
    5 },
    6 _bind: function() {
    7 this._on({
    8 save: this._submit
    9 })
    10 },
    11 _submit: function(e, data) {
    12 this._rollback();
    13 if (false !== this._beforeSubmit(e.type, data)) {
    14 this.element.trigger('submit', e);
    15 }
    16 }
    17});
  • You must use DOM event bubbling to perform one-way communication between a child widget and its parent widget.

  • Widgets must comply with the Law of Demeter principle.

    Do not instantiate a widget or call a widget's methods inside another widget.

  • Make widgets abstract enough so that they can be used anywhere in the code.

    For example, the mage.dropdown widget is applicable in many other scenarios, unlike mage.topShoppingCart.

  • Place abstract, share-able widgets under the <install dir>/pub/lib/<your company> directory so that other applications can access them.

    For example:

    Copied to your clipboard
    1/pub
    2 /lib
    3 /magento
    4 dropdown.js
    5 validation.js
    6 dialog.js
  • Place Adobe Commerce and Magento Open Source-specific widgets under the <install dir>/app/code/<namespace>/<module-name>/view/<area-name>/js directory.

    For example:

    Copied to your clipboard
    1/app
    2 /code
    3 /Mage
    4 /DesignEditor
    5 /view
    6 /frontend
    7 /js
    8 vde-block.js
    9 vde-container.js

Architecture#

  • Use an underscore prefix to declare private widget methods.

    Properties without an underscore prefix are accessible using the jQuery Widget factory public API.

    Copied to your clipboard
    1// Declaration of the backend.accordion widget
    2$.widget('mage.accordion', {
    3 _create: function() {
    4 this.header = this.element.find(this.options.header);
    5 this.icon = $(this.options.icon).prependTo(this.header);
    6 }
    7});
  • Start a widget's element selection with this.element

  • Widgets must not interact with DOM elements selected using this.element.parent(), this.element('selector'), or this.element.closest('selector').

    This reduces the number of widget conflicts because widgets interact only with their child elements.

  • Widget options should have default values.

    Use a null value if there is no default value for an option.

  • Pass as widget options all DOM selectors used by that widget.

  • Use the _setOption method to process required, immediate state changes.

  • Use the public widget API to call widget methods to allow chaining widget methods.

    Copied to your clipboard
    1// Call the 'open' method on the menu widget using the public widgets API
    2$('selector')
    3.menu('open')
    4.addClass('ui-state-active');
  • Handle widget initialization if there is a logical action to perform on successive calls to the widget with no arguments.

    The widget factory automatically fires the _create() and _init() methods during initialization, in that order and prevents multiple instantiations of the same element.

    The _create() method is called only once for each widget instance and _init() is called each time the widget is called without arguments.

  • When a widget is destroyed, the attached element should be left exactly like it was before attachment.

    Common tasks for this include:

    • Removing or adding any CSS classes the widget added/removed to the element.
    • Detaching any elements the widget added to the DOM.
    • Destroying any widgets that the widget applied to other elements.
  • Bind event handlers using the _bind() method to make it easy to find what events the widget reacts on.

  • Bind events using the on() method.

    Benefits:

    • Delegation is supported using selectors in the event names. For example: click.foo.
    • Maintains proper this context inside the handlers, so it is not necessary to use the $.proxy() method.
    • Event handlers are automatically namespaced and cleaned up on destruction.
  • Privacy
  • Terms of Use
  • Do not sell my personal information
  • AdChoices
Copyright © 2022 Adobe. All rights reserved.