Search code examples
javascriptjqueryyui

Accessing variables across different scopes in Javascript & YUI 3


I'm new to YUI 3 and YUI in general. I'm trying to pass data between classes and methods.

In this example I'm using the gallery-sm-treeview plugin to build a file tree. There's a class named TreeView to initialize and render the tree. There's another class named MenuBar where I want to access some of the plugin-specific methods through TreeView's getter method.

However, the variable var treeview inside the YUI().use() scope is of course not accessible from outside. How to do it?

YUI.add('treetool.TreeView', function(Y) {

  Y.treetool.TreeView = Class.extend({

    init : function(elementId) {

      YUI({
        gallery: 'gallery-2013.06.20-02-07'}).use('gallery-sm-treeview', function (Y) {

          // Create a new TreeView with a few nodes.
          var treeview = new Y.TreeView({

              // Tell the TreeView where to render itself.
              container: elementId,

              // Populate the treeview with some tree nodes. 
              nodes: [
                  {label: 'Node 1'},
                  {label: 'Node 2', children: [
                      {label: 'Child 1'},
              ]
          });

          // Render the treeview inside the #treeview element.
          treeview.render();

        });          
    },  

    getSomeData : function () {

      return treeview.getSelectedNodes();      

    }

  }); 

}, '0.0.1', {
  requires : [ 'jquery' ]
});

and

YUI.add('treetool.MenuBar', function(Y) {

  Y.treetool.MenuBar = Class.extend({

    init : function(treeObj) {

      var someData = treeObj.getSomeData();

    },  
  });

}, '0.0.1', {
  requires : [ 'jquery' ]
});

Solution

  • It might not be the "best" way to do it, but one way would be to define the treeview variable in a scope that is available in both places.

    YUI.add('treetool.TreeView', function(Y) {
        var treeview;
        //...
    

    and

    treeview = new Y.TreeView({ // removed "var "