Pergunta

In the snippet below, I am trying to access testFunction() which is inside YUI block. What is the correct way of doing it?

var obj = YUI().use('node', 'event', 'io-base', 'json-parse', function(Y){
    function testFunction() {
        console.log('Inside Function');
    }
});

obj.testFunction();
Foi útil?

Solução

Your code isn't currently working for two reasons;

first, the testFunction function you're declaring isn't going to be visible. Changing the code to

var obj = YUI().use('node', 'event', 'io-base', 'json-parse', function(Y){
    Y.testFunction = function() {
        console.log('Inside Function');
    }
});

fixes that part. The Y passed to your function will be returned from YUI.use(), so assigning it to Y makes it visible.

The second problem is that the call to obj.testFunction() is going to happen before YUI has loaded the modules you need, so at that point, obj (an instance of YUI) will not have a testFunction in it. If you make the code change above, you'll be able to call obj.testFunction() in the browser console, because it'll have been loaded by that point.

The best bet is to place your testFunction into a module, then use that module in later code:

YUI.add('testFunction', function (Y) {
   Y.testFunction = function() {
        console.log('Inside Function');
    };
}, '1.0.0', {
    requires: ['node', 'event', 'io-base', 'json-parse']
});

var obj = YUI().use('testFunction', function(Y){
      Y.testFunction();
});

http://jsfiddle.net/u2XPA/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top