JavaScript & AMD modules

What are they?

AMD modules are a a new way of writing Javascript modules, replacing the existing YUI modules. These have been introduced in Moodle 2.9 and will be available in the next major release of Totara.

How do I write them?

Totara uses requireJS to load the the modules and grunt to minify them (this also uses shifter to create the old YUI modules).

A simple template for a new javascript file would be:

define(['jquery', <other dependencies>], function ($, <other variables>) {
    var objectone = {
        init: function (args) {
            //init function
        },
        //other functions for your module
    }
    
    return objectone;
});

My module is too big for one file

That's fine. Using requireJS, you can load each file as needed. Within your code add the following snippet:

require('<frankensense plugin name>/<modulename>', function(<module export value>) {
    // use module export value here
});

Minification

While developing with $CFG->cachejs set to false, Totara uses the files that are found in amd/src for your components. While this is great for development in that it allows you to see your changes immediately, without having to do anything, it is not ideal on a live site.

Once $CFG->cachejs is set to true, Totara looks first for a file in /amd/build/ to use and if not then, looks in /amd/src/. Totara uses Grunt to "build" (minify) your JavaScript from the src directory into the build directory. For installation instructions see https://docs.moodle.org/dev/Javascript_Modules#Install_grunt. Note that behat uses the minified versions.

More information

https://docs.moodle.org/dev/Javascript_Modules

http://requirejs.org/

How do I call them from PHP?

By making a call to:

$PAGE->requires->js_call_amd('file', 'initfunction')

where file is the location of the file to add and initfunction is the javascript function that initialises the module.

ES6 Support?

Totara version 12+ supports some basic ES6 features, for a full list of supported features see ES6 functionality.