Skip to content
intermediate Phase 55 · Frontend JavaScript

AMD Modules in Magento

Understanding AMD module pattern in Magento 2: define, require, module patterns, and Magento JavaScript architecture

45m
0 problems
Topic Progress 0%

AMD Pattern Basics

What is AMD?

AMD (Asynchronous Module Definition) is a JavaScript module pattern that loads modules asynchronously.

Basic Module Definition

define([
    'jquery',
    'mage/url',
    'mage/translate'
], function($, url, $t) {
    'use strict';
    
    // Module code here
    return {
        init: function(config) {
            console.log($t('Hello World'));
        }
    };
});

Module Structure

define([
    'dependency1',
    'dependency2'
], function(dep1, dep2) {
    'use strict';
    
    // Private variables
    var privateVar = 'private';
    
    // Private function
    function privateFunction() {
        return privateVar;
    }
    
    // Public API
    return {
        publicMethod: function() {
            return dep1.method();
        }
    };
});

Key Concepts

  • define(): Creates a module
  • require(): Loads a module
  • Dependencies are loaded asynchronously
  • Modules are cached after first load

Define and Require

define() Syntax

// Simple module
define([], function() {
    return {
        value: 42
    };
});

// With dependencies
define(['jquery'], function($) {
    'use strict';
    
    return function() {
        $(document).ready(function() {
            console.log('Ready!');
        });
    };
});

// Named module
define('Vendor_Module/js/module', [
    'jquery'
], function($) {
    'use strict';
    
    return {};
});

require() Syntax

// Load and use
require(['jquery'], function($) {
    'use strict';
    
    $(function() {
        console.log('DOM ready');
    });
});

// Multiple modules
require(['jquery', 'mage/url'], function($, url) {
    'use strict';
    
    var buildUrl = url.build('path/to/route');
});

// With error handler
require(['myModule'], function(myModule) {
    myModule.init();
}, function(error) {
    console.error('Load failed:', error);
});

CommonJS vs AMD

// CommonJS (Node.js)
var $ = require('jquery');

// AMD (Browser)
define(['jquery'], function($) {
    // Use $
});

Module Patterns

Revealing Module Pattern

define(['jquery'], function($) {
    'use strict';
    
    var privateData = {};
    
    function privateMethod() {
        return 'private';
    }
    
    return {
        publicMethod: function() {
            return privateMethod();
        },
        getData: function(key) {
            return privateData[key];
        }
    };
});

Factory Pattern

define([], function() {
    'use strict';
    
    return function(config) {
        return {
            init: function() {
                console.log(config.apiKey);
            },
            getData: function() {
                return config.data;
            }
        };
    };
});

Singleton Pattern

define([], function() {
    'use strict';
    
    var instance = null;
    
    function createInstance() {
        return {
            value: Math.random()
        };
    }
    
    return {
        getInstance: function() {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
});

Observer Pattern

define(['jquery'], function($) {
    'use strict';
    
    var events = $({});
    
    return {
        on: function(event, callback) {
            events.on(event, callback);
        },
        trigger: function(event, data) {
            events.trigger(event, data);
        }
    };
});

Magento JavaScript Architecture

Magento JS Components

// Widget pattern
define([
    'jquery',
    'jquery/ui'
], function($) {
    'use strict';
    
    $.widget('mage.customWidget', {
        options: {
            selector: '.element'
        },
        
        _create: function() {
            this._on(this.options.selector, {
                'click': this.handleClick
            });
        },
        
        handleClick: function() {
            console.log('Clicked!');
        }
    });
    
    return $.mage.customWidget;
});

UI Component Pattern

define([
    'uiComponent'
], function(Component) {
    'use strict';
    
    return Component.extend({
        defaults: {
            template: 'Vendor_Module/component'
        },
        
        initialize: function() {
            this._super();
            return this;
        },
        
        getData: function() {
            return this.data();
        }
    });
});

Magento JS Utilities

Utility Purpose
mage/url URL building
mage/translate i18n translations
mage/storage AJAX requests
mage/modal Modal dialogs
mage/collapsible Collapsible sections
mage/dropdown Dropdown menus

Loading Order

// 1. RequireJS loads dependencies
require(['jquery', 'mage/url'], function($, url) {
    
    // 2. DOM ready
    $(function() {
        
        // 3. Initialize component
        var component = $('#element').componentName({
            option: 'value'
        });
    });
});

Quiz

1. What does AMD stand for?

Question 1 options

2. What is the purpose of define()?

Question 2 options

3. Which Magento utility builds URLs?

Question 3 options

Flashcards

Question

What does AMD stand for?

Answer

Asynchronous Module Definition

Question

What does define() do?

Answer

Creates a new AMD module

Question

What does require() do?

Answer

Loads and uses an AMD module

Question

What is the Magento widget pattern?

Answer

$.widget('mage.name', { ... })

Question

What utility builds URLs?

Answer

mage/url

Revision Notes

Key Takeaways

  • 1. AMD loads modules asynchronously in the browser
  • 2. define() creates modules, require() loads them
  • 3. Modules return public API, keep private state
  • 4. Magento uses widget pattern for jQuery components
  • 5. Common utilities: mage/url, mage/translate, mage/storage

Interview Tips

  • Explain the AMD pattern and its benefits
  • Know the difference between define() and require()
  • Discuss module patterns used in Magento
  • Be ready to create a Magento JavaScript module

Cheat Sheet

AMD Module:
define(['dep1', 'dep2'], function(dep1, dep2) {
    'use strict';
    return { publicMethod: function() {} };
});

Load Module:
require(['module'], function(mod) { mod.init(); });

Magento Widget:
$.widget('mage.name', {
    _create: function() { /* init */ }
});