How do I call a basic YUI3 function from within a

2019-06-05 11:31发布

问题:

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.

回答1:

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.



回答2:

You can do like this:

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

Then, you can call changeContent by calling APP.changeContent(message); from anywhere you want. Hope this helps. :D



标签: yui yui3