Search code examples
moduleyui3instances

Sharing variable around different instances of YUI


I have made up the custom module as :

YUI.add('util', function(Y) {
   Y.namespace('com.myCompany');
   var NS = Y.com.myCompany;
        NS.val = undefined;
}, '3.3.0', {
   requires : []
});

What I am trying to do is share this variable val in the instances where I use this module "util". As in

YUI().use("util","node","event",function (Y) {
    Y.namespace('com.myCompany');
    var MV = Y.com.myCompany;
    var setVal = function(e){
        MV.val = 10;
}
   Y.on("click", setVal,"#one");
  });

Now if I want to get this in other instance I am doing as the following:

 YUI().use("util","node","event",function (Y) {
        Y.namespace('com.myCompany');
        var MV = Y.com.myCompany;
        var getVal = function(e){
            alert(MV.val);
        }
       Y.on("click", getVal,"#two");
    });

But this does not seem to be working. Is there a way to get this behavior. I am doing this only to split up the code.


Solution

  • In this case, you should only create one sandbox. The correct way to break up your code is to use YUI.add to create the modules and specify their dependencies. One way to do this is to structure your code as follows:

    // util.js
    YUI.add('util', function (Y) {
        var NS = Y.namespace('com.MyCompany'); 
        NS.val = null;
    }, 'version', {
        requires: ['some', 'dependencies']
    });
    
    // one.js
    YUI.add('one', function (Y) {
        var NS = Y.namespace('com.MyCompany');
        Y.on('click', function (e) { NS.val = 23; }, '#one');
    }, 'version', {
        requires: ['util']
    });
    
    // two.js
    YUI.add('two', function (Y) {
        var NS = Y.namespace('com.MyCompany');
        Y.on('click', function (e) { alert(NS.val); }, '#two');
    }, 'version', {
        requires: ['util']
    });
    
    // index.html
    <button id="one">Set the value</button>
    <button id="two">Get the value</button>
    
    <script>
        YUI.use('one, 'two', 'node', 'event', function (Y) {
            // main application logic here
        });
    </script>
    

    This allows you to break up your code into separate modules that share the same YUI sandbox instance.

    Note also YUI.namespace returns the namespace in question, so you don't need the extra variables.