b-qscg
Last Updated: February 25, 2016
·
1.822K
· alroman

Extending a Moodle YUI 3 module

Our Moodle course format offers the functionality of overriding the standard resource edit icons with actual text. In Moodle 2.3 we achieve this by overriding the core renderers and core YUI modules. This is easier said than done because we need to preserve all the functionality that you get with icons, including the fancy AJAX. We could have rewritten the JS for that, but we found that it's possible to override core Moodle's YUI modules instead.

The AJAX functionality was defined in core modules. Moodle core modules are defined like any standard YUI module as follows:

YUI.add('moodle-module', function(Y) {
...
// Class definition
var SOMECLASS = function () {
     SOMECLASS.superclass.constructor.apply(this, arguments);
}

// Define your class
...

// Moodle modules usually extend some other core module
Y.extend(SOMECLASS, Y.Base, {
     some_method : function(param) {
         // Do something...
         return foo;
     }, {
         NAME: ...,
         ATTRIB: ...
  });

// Define a global variable
M.somcleass = M.somclass || {};
M.someclass.obj = SOMECLASS;

}, '@VERSION@', {requires: [ ... ]});

Suppose you wanted to extend that module, you'd do something like:

YUI.add('my-module', function(Y) {

var MYCLASS = function() {
     MYCLASS.superclass.constructor.apply(this, arguments);
}

// Inherit from parent class
Y.extend(MYCLASS, M.someclass.obj);

 // Now extend
 Y.prototype.custom_method = function() {
 // Do something..
 }
 // 
 }, '@VERSION@', {requires: ['moodle-module']});

This is plain 'ol class inhertiance. Now suppose you wanted to call a parent method and do something interesting after it's been called.

...
// Call parent method
MYCLASS.prototype.some_method = function(param) {
    // Call parent method
    var foo = MYCLASS.superclass.some_method.apply(this, [param]);

    // Do something after you call the parent method..
    // Perhaps override the images with text!

    // return what's expected
    return foo;
}

The end.