Search code examples
yuiyui3

How do I call a basic YUI3 function from within a normal JavaScript function?


I'd like to call a simple YUI3 function from within a JavaScript function. Here is some code that does what I want in a very verbose way:

function changeContent (message) {
    YUI().use("node", function(Y) {
        Y.all('#content-div').setContent(message);
    });
}

Is there a better way to do this?

NOTE: I don't want to attach this function to any event, I just want a global changeContent() function available.


Solution

  • If you want the API to exist outside of the YUI().use(...function (Y) { /* sandbox */ }), you can capture the returned instance from YUI().

    (function () { // to prevent extra global, we wrap in a function
        var Y = YUI().use('node');
    
        function changeContent(message) {
            Y.one('#content-div').setContent(message);
        }
    
        ...
    })();
    

    Be aware that there is a race condition here if you use the seed file (yui-min.js) and dynamic loader to pull in the other modules. changeContent could be called before the Node API is loaded and added to Y. You can avoid this by using a combo script up front. You can get the combo script url from the YUI 3 Configurator. There is a performance penalty for loading the modules in a blocking manner up front. You may or may not notice this in your application.