Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Useful core Javascript modules: Difference between revisions

From MoodleDocs
(Add core/loadingicon)
m (Text replacement - "<code (.*)>" to "<syntaxhighlight lang="$1">")
 
(4 intermediate revisions by 2 users not shown)
Line 6: Line 6:


Example of using config module:
Example of using config module:
<code javascript>
<syntaxhighlight lang="javascript">
require(['core/config’], function(mdlcfg) {
require(['core/config’], function(mdlcfg) {
     console.log(mdlcfg.wwwroot); // outputs the wwwroot of moodle to console
     console.log(mdlcfg.wwwroot); // outputs the wwwroot of moodle to console
});
});
</code>
</syntaxhighlight>


== Language strings (core/str) ==
== Language strings (core/str) ==


Example of using language strings module (retrieved via ajax, if the string is not yet loaded)
Example of using language strings module (retrieved via ajax, if the string is not yet loaded)
<code javascript>
<syntaxhighlight lang="javascript">
require([‘core/str’], function(str) {
require([‘core/str’], function(str) {
     // start retrieving the localized string; store the promise that some time in the future the string will be there.
     // start retrieving the localized string; store the promise that some time in the future the string will be there.
Line 26: Line 26:
     });
     });
});
});
</code>
</syntaxhighlight>


You can also convert multiple strings and add parameters in a single call
You can also convert multiple strings and add parameters in a single call
<code javascript>
<syntaxhighlight lang="javascript">
     // Real example from user/amd/src/status_field.js
     // Real example from user/amd/src/status_field.js
     var strings = [
     var strings = [
Line 49: Line 49:
         console.log(results);
         console.log(results);
     });
     });
</code>
</syntaxhighlight>


The string will be retrieved via AJAX request on the first use and cached in browser local storage until purge caches or site upgrade
The string will be retrieved via AJAX request on the first use and cached in browser local storage until purge caches or site upgrade


IT IS NOT RECOMMENDED to call:
IT IS NOT RECOMMENDED to call:
<code php>
<syntaxhighlight lang="php">
$PAGE->requires->string_for_js('edita', 'core'); // You do not need this!
$PAGE->requires->string_for_js('edita', 'core'); // You do not need this!
</code>
</syntaxhighlight>


Because:
Because:
Line 66: Line 66:


Examples:
Examples:
<code javascript>
<syntaxhighlight lang="javascript">
require(['core/notification’], function(notification) {
require(['core/notification’], function(notification) {
     notification.alert('Hello', 'Welcome to my site!', 'Continue');
     notification.alert('Hello', 'Welcome to my site!', 'Continue');
});
});
</code>
</syntaxhighlight>


Strings and notifications:
Strings and notifications:
<code javascript>
<syntaxhighlight lang="javascript">
require(['core/str', 'core/notification’], function(str, notification) {
require(['core/str', 'core/notification’], function(str, notification) {
                 str.get_strings([
                 str.get_strings([
Line 87: Line 87:
                 ).fail(notification.exception);
                 ).fail(notification.exception);
});
});
</code>
</syntaxhighlight>


== URL module (core/url) ==
== URL module (core/url) ==


Useful Functions:
Useful Functions:
<code javascript>
<syntaxhighlight lang="javascript">
// Generate an absolute URL by using the relative path to a file and optionally slash arguments
// Generate an absolute URL by using the relative path to a file and optionally slash arguments
url.fileUrl(relativeScript, slashArgs)
url.fileUrl(relativeScript, slashArgs)
Line 99: Line 99:
// Generates an image url using the filename of the image and the Moodle component (core, plugin, etc.) where it can be found
// Generates an image url using the filename of the image and the Moodle component (core, plugin, etc.) where it can be found
url.imageUrl(imagename, component)
url.imageUrl(imagename, component)
</code>
</syntaxhighlight>


Example:
Example:


<code javascript>
<syntaxhighlight lang="javascript">
// Prerequisites:
// Prerequisites:
// - A Javascript file is present under $CFG->wwwroot."/path/to/file.js"
// - A Javascript file is present under $CFG->wwwroot."/path/to/file.js"
Line 110: Line 110:
     console.log("Generated URL: " + url);
     console.log("Generated URL: " + url);
});
});
</code>
</syntaxhighlight>


== Ajax Module (core/ajax) ==
== Ajax Module (core/ajax) ==
Line 122: Line 122:
If you want to add a hierarchical interface, you should use the tree module. It will handle user interaction and accessibility for you.
If you want to add a hierarchical interface, you should use the tree module. It will handle user interaction and accessibility for you.


<code javascript>
<syntaxhighlight lang="javascript">
define(['jquery', 'core/tree'], function($, Tree) {
define(['jquery', 'core/tree'], function($, Tree) {
     return {
     return {
Line 130: Line 130:
     };
     };
});
});
</code>
</syntaxhighlight>


Read more about the [[Tree]] module
Read more about the [[Tree]] module
Line 138: Line 138:


If you'd like to add a modal to your page the modal modules will handle all of the magic for you, all you need to bring is your content!
If you'd like to add a modal to your page the modal modules will handle all of the magic for you, all you need to bring is your content!
<code javascript>
<syntaxhighlight lang="javascript">
require(['jquery', 'core/modal_factory'], function($, ModalFactory) {
require(['jquery', 'core/modal_factory'], function($, ModalFactory) {
   var trigger = $('#create-modal');
   var trigger = $('#create-modal');
Line 153: Line 153:
   });
   });
});
});
</code>
</syntaxhighlight>


Read more about the [[AMD_Modal]] module
Read more about the [[AMD_Modal]] module
Line 171: Line 171:
Read more about the [[AMD_pubsub]] module
Read more about the [[AMD_pubsub]] module


== Loading icons (core/loadicon) ==
== Loading icons (core/loadingicon) ==
{{Moodle 3.7}}
{{Moodle 3.7}}


A simple module to add a loading icon which is easily removable, either via resolving a Promise, or removes itself automatically when another Promise is resolved.
A simple module to add a loading icon which is easily removable, either via resolving a Promise, or removes itself automatically when another Promise is resolved.
<syntaxhighlight lang="javascript">
define(['jquery', 'core/ajax', 'core/loadingicon'], function($, Ajax, LoadingIcon) {
  return {
    demo1: function() {
      // Add a loading icon which can be removed by the caller.
      var exampleElement = $('.example');
      var loadingIcon = LoadingIcon.addIconToContainerWithPromise(exampleElement);
      // To remove:
      loadingIcon.resolve();
    },
    demo2: function() {
      // Add a loading icon which would be removed when the AJAX request completes.
      var exampleElement = $('.example');
      var requests = Ajax.call([{
          methodname: 'some_method',
      }]);
      LoadingIcon.addIconToContainerRemoveOnCompletion(exampleElement, requests);
      requests[0].then(function(request) {
          // Do something.
      })
      .catch;
    },
  };
});
</syntaxhighlight>


==See also==
==See also==

Latest revision as of 08:25, 15 July 2021

Moodle 2.9


The source code for all these modules (and a number of others) can be found in lib/amd/src.

Configuration settings (core/config)

Example of using config module:

require(['core/config], function(mdlcfg) {
    console.log(mdlcfg.wwwroot); // outputs the wwwroot of moodle to console
});

Language strings (core/str)

Example of using language strings module (retrieved via ajax, if the string is not yet loaded)

require([core/str], function(str) {
    // start retrieving the localized string; store the promise that some time in the future the string will be there.
    var editaPresent = str.get_string('edita', 'core', stringargument);
    // as soon as the string is retrieved, i.e. the promise has been fulfilled,
    // edit the text of a UI element so that it then is the localized string
    // Note: $.when can be used with an arbitrary number of promised things
    $.when(editaPresent).done(function(localizedEditString) {
         $("someUIElementSelector").text = localizedEditString;
    });
});

You can also convert multiple strings and add parameters in a single call

    // Real example from user/amd/src/status_field.js
    var strings = [
        {
            key: 'unenrol',
            component: 'enrol'
        },
        {
            key: 'unenrolconfirm',
            component: 'enrol',
            param: {
                user: parentContainer.data('fullname'),
                course: parentContainer.data('coursename'),
                enrolinstancename: parentContainer.data('enrolinstancename')
            }
        }
    ];
    str.get_strings(strings).then(function (results) {
        console.log(results);
    });

The string will be retrieved via AJAX request on the first use and cached in browser local storage until purge caches or site upgrade

IT IS NOT RECOMMENDED to call:

$PAGE->requires->string_for_js('edita', 'core'); // You do not need this!

Because:

  • The list of strings used now needs to be maintained in 2 places
  • The strings are always sent, and bloat the page size even if they are not used
  • All strings fetched via the AJAX method above are cached in browser local storage anyway, so these strings will never be used 99% of the time

Notifications (core/notification)

Examples:

require(['core/notification’], function(notification) {
    notification.alert('Hello', 'Welcome to my site!', 'Continue');
});

Strings and notifications:

require(['core/str', 'core/notification’], function(str, notification) {
                str.get_strings([
                        {'key' : 'delete'},
                        {'key' : 'confirmdeletetag', component : 'tag'},
                        {'key' : 'yes'},
                        {'key' : 'no'},
                    ]).done(function(s) {
                        notification.confirm(s[0], s[1], s[2], s[3], function() {
                            window.location.href = href;
                        });
                    }
                ).fail(notification.exception);
});

URL module (core/url)

Useful Functions:

// Generate an absolute URL by using the relative path to a file and optionally slash arguments
url.fileUrl(relativeScript, slashArgs)
// Generate an absolute URL from the given relative path, include the URL parameters and possibly the current session key
url.relativeUrl(relativePath, params, includeSessionKey)
// Generates an image url using the filename of the image and the Moodle component (core, plugin, etc.) where it can be found
url.imageUrl(imagename, component)

Example:

// Prerequisites:
// - A Javascript file is present under $CFG->wwwroot."/path/to/file.js"
require(['core/url'], function(url) {
    url.fileUrl("/path/to/file.js", "");
    console.log("Generated URL: " + url);
});

Ajax Module (core/ajax)

The preferred way to write new ajax interactions in Moodle is to use the javascript module "core/ajax" which can directly call existing web service functions. This saves having to worry about security in ajax functionality because it's all done for you.

For the full story, see AJAX

Tree (core/tree)

Moodle 3.1

If you want to add a hierarchical interface, you should use the tree module. It will handle user interaction and accessibility for you.

define(['jquery', 'core/tree'], function($, Tree) {
    return {
        init: function() {
            new Tree("css/jquery selector of the tree container");
        }
    };
});

Read more about the Tree module

Modal (core/modal)

Moodle 3.2


If you'd like to add a modal to your page the modal modules will handle all of the magic for you, all you need to bring is your content!

require(['jquery', 'core/modal_factory'], function($, ModalFactory) {
  var trigger = $('#create-modal');
  ModalFactory.create({
    title: 'test title',
    body: '<p>test body content</p>',
    footer: 'test footer content',
  }, trigger)
  .done(function(modal) {
    // Do what you want with your new modal.

    // Maybe... add a class to the modal dialog, to be able to style it.
    modal.getRoot().addClass('mydialog');
  });
});

Read more about the AMD_Modal module

Paged content (core/paged_content_factory)

Moodle 3.6


If you need to create a paged content region to asynchronously load the pages as the user requests them then you can use the paged content modules.

Read more about the AMD_paged_content module

PubSub (core/pubsub)

Moodle 3.6


A simple module to do event subscription and publishing in JavaScript without the need for jQuery.

Read more about the AMD_pubsub module

Loading icons (core/loadingicon)

Moodle 3.7


A simple module to add a loading icon which is easily removable, either via resolving a Promise, or removes itself automatically when another Promise is resolved.

define(['jquery', 'core/ajax', 'core/loadingicon'], function($, Ajax, LoadingIcon) {
  return {
    demo1: function() {
      // Add a loading icon which can be removed by the caller.
      var exampleElement = $('.example');

      var loadingIcon = LoadingIcon.addIconToContainerWithPromise(exampleElement);

      // To remove:
      loadingIcon.resolve();
    },

    demo2: function() {
      // Add a loading icon which would be removed when the AJAX request completes.
      var exampleElement = $('.example');

      var requests = Ajax.call([{
          methodname: 'some_method',
      }]);
      LoadingIcon.addIconToContainerRemoveOnCompletion(exampleElement, requests);

      requests[0].then(function(request) {
          // Do something.
      })
      .catch;
    },
  };
});

See also