Create YUI3 Module For Moodle
Warning: This page is no longer in use. The information contained on the page should NOT be seen as relevant or reliable. |
Please see How to create a YUI 3 module for more up to date information.
Introduction
The flexibility of JavaScript is potential for good or evil. For one side, it enables you to write really smart code, for another side, it could decrease the readability of your source code, for complex project like Moodle, readability is an essential factor to write code.
Since we introduce YUI3 in moodle 2.0, the use of JavaScript in Moodle has been improved a lot. We are creating more and more YUI3 modules to replace previous all-in-one javascript-static.js to make JavaScipt Scalable. It is time to have a standard way to create YUI3 modules for Moodle. So I wrote this proposal for further development, feel free to comment/change this page.
Methods
The YUI3 recommended way
Registering and defining a module by YUI3 method.
NOTE: It is not necessary to use Y.filepicker here, we can also register to M.filepicker
Sample code
YUI.add('filepicker', function(Y) {
var filepicker = function(args) {
filepicker.superclass.constructor.apply(this, arguments);
}
filepicker.NAME = "MoodleFilePicker";
Y.extend(filepicker, Y.Base, {
initializer: function(args) {
}
});
Y.filepicker = filepicker;
}, '3.0.1', {requires: ['io', 'node', 'event']});
To use this module:
Y.use('filepicker', function(Y) {
var fp = new Y.filepicker({});
});
Pros
- No Global Namespace Pollution
- YUI3 standard way to create modules
Cons
- Maybe incompatible with future YUI4
Use anonymous function
Sample code
M.filepicker = (function() {
var filepicker = function(args) {
filepicker.superclass.constructor.apply(this, arguments);
}
filepicker.NAME = "MoodleFilePicker";
Y.extend(filepicker, Y.Base, {
initializer: function(args) {
}
});
return filepicker;
})();
To use this module:
Y.use('filepicker', function(Y) {
var fp = new M.filepicker({});
});
Pros
- No Global Namespace Pollution
Cons
Use init() method
Sample code
M.filepicker = {
init: function(args) {
var filepicker = function(args) {
filepicker.superclass.constructor.apply(this, arguments);
}
filepicker.NAME = "MoodleFilePicker";
Y.extend(filepicker, Y.Base, {
initializer: function(args) {
// initialize object
}
});
new filepicker;
}
};
To use this module:
Y.use('filepicker', function(Y) {
M.filepicker.init({});
});
Pros
- No Global Namespace Pollution
Cons
- Not quite OOP
Sample code
M.core_filepicker = {};
// define a class
M.core_filepicker.ui = function() {
this.classname = '';
}
M.core_filepicker.prototype.instancemethod = function() {
}
//static method
M.core_filepicker.init = function() {
new M.core_filepicker.ui();
}