Useful core Javascript modules: Difference between revisions
From MoodleDocs
Damyon Wiese (talk | contribs) |
No edit summary |
||
Line 34: | Line 34: | ||
* The strings are always sent, and bloat the page size even if they are not used | * 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 | * 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: | |||
<code javascript> | |||
require(['core/notification’], function(notification) { | |||
notification.alert('Welcome', 'Hello to my site!', 'Continue'); | |||
}); | |||
</code> | |||
Strings and notifications: | |||
<code javascript> | |||
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); | |||
}); | |||
</code> | |||
==See also== | ==See also== |
Revision as of 02:11, 27 July 2015
Moodle 2.9
Configuration settings (core/config)
Example of using config module:
require(['core/config’], function(mdlcfg) {
cosole.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) {
str.get_string('edita', 'core', stringargument).done(function(s) {
console.log(s);
}).fail(console.log(e));
});
The string will be retrieved via AJAX request on the first use. To avoid ajax call you could preload strings in PHP:
global $PAGE;
$PAGE->requires->string_for_js('edita', 'core');
BUT ITS NOT RECOMMENDED!!!
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('Welcome', 'Hello 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);
});