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

▼魔方 西西 提交于 2019-12-08 08:47:27

问题


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



来源:https://stackoverflow.com/questions/3019805/how-do-i-call-a-basic-yui3-function-from-within-a-normal-javascript-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!