Created
October 22, 2011 01:04
-
-
Save juandopazo/1305379 to your computer and use it in GitHub Desktop.
Loading AMD modules from YUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 everything that looks like a file | |
// Any other AMD module must be declared in the "modules" config like any other module | |
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 if (lastModule) { | |
throw new Error('Multiple anonymous defines found'); | |
} else { | |
lastModule = { | |
deps: dependencies, | |
mod: module | |
}; | |
} | |
} | |
}(this)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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;
});