public
Created

Loading AMD modules from YUI

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
(function (window) {
 
var lastModule;
 
// configFn for all patterns that match an AMD-like module
// For now, only modules starting with ./ or ../ are recognized as being AMD-like
// Support for regular expressions in the patterns configuration was requested in ticket #2531324
// In the future the goal is to filter out YUI core and Gallery modules from anything else
function defConfigFn(config) {
config.fullpath = config.name;
}
 
function registerModule(name, dependencies, module) {
YUI.add(name, function (Y) {
/*
* Object modules get mixed into the Y instance for a more YUI-like experience
* The rest is stored in a property with the same name as the module's
*/
if (typeof module === 'object') {
Y.mix(Y, module, true);
} else {
Y[name] = module;
}
// dependencies should be declared beforehand or handled by the Loader, not by this script
}, '', { requires: dependencies });
}
 
YUI.GlobalConfig = {
groups: {
amd: {
patterns: {
'./': {
configFn: defConfigFn
},
'../': {
configFn: defConfigFn
}
}
}
},
onProgress: function (e) {
if (lastModule) {
registerModule(e.name, lastModule.deps, lastModule.mod);
lastModule = null;
}
}
};
 
window.define = function define(name, dependencies, module) {
if (arguments.length === 1) {
module = name;
dependencies = [];
name = '';
} else if (arguments.length === 2) {
module = dependencies;
if (typeof name === 'string') {
dependencies = [];
} else {
dependencies = name;
name = '';
}
}
if (typeof module === 'function') {
module = module();
}
// store unnamed modules and register them later
if (name !== '') {
registerModule(name, dependencies, module);
} else {
lastModule = {
deps: dependencies,
mod: module
};
}
}
 
}(this));

in order for the callback Y.add(...) (line 15) to work
config module NAME must match the define('NAME', ...) defined in the AMD module
YUI({modules: { 'NAME': {fullpath: '...'}}).use('NAME', ...)

ie.
window.define.amd = {jQuery: true}; // needed to load jquery as an AMD module
YUI({modules: {'jquery': {fullpath:'....'}}).use('jquery', function(Y) {
var $ = Y.jquery;
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.