Understanding YUI module loading and attaching
-
06-12-2019 - |
Question
I am using the latest version of the Yahoo User Interface
.
I am looking at the YUI global
object's docs and I have some questions.
I would like to know when is a module loaded and when is it attached to a specific instance?
YUI().use('calendar', function (Y) {
// I assume that when we are here that the calendar module has been loaded?
// But when is it attached to this instance of YUI?
});
How do I create multiple YUI sandboxes if the first instance is declared like this:
var Y = YUI();
Y.use('node', 'event', function (Y) {
});
Would you still pass Y into both instances?
La solution
Answer to the second question first:
The YUI()
function creates the sandbox. So
var Y1 = YUI();
var Y2 = YUI();
would be two separate sandboxes, and Y1
and Y2
will know nothing about each other.
However you can do something like this.
Y1 = YUI();
Y1.use('calendar', function (Y) {
Y.myCalendar = new Y.Calendar().render(Y.one('body'));
});
setTimeout( function () {
Y1.use(function (Y) {
Y.myCalendar.on('dateClick', function (e) {
alert('date clicked');
});
});
}, 100);
The global Y1
becomes the local Y
in each of the use
functions. This also illustrates out an answer to your first question. The setTimeout
is used in this example because each use
function attaches modules and runs its functions asynchronously to one another. Without the setTimeout
you will most likely get an error from the second use
because it will run before myCalendar
is defined by the first use
.
Each use
will perform its own lazy loading of modules. If the modules are already loaded it only needs to attach them to the YUI instance. In practice most applications only employ one use
per sandbox.
Of course there's lots more info and details in the YUI docs.