NorCalKnockOut
NorCalKnockOut

Reputation: 878

How would I refactor this javascript to not use a global?

var groups;

function findGroups {
  getGroups().then(function (g) {
    groups = g;
  });
}

function foo() {
  var a = groups[0];  //or something along those lines.
  //access the properties of `g`
}

I want to access g in other functions throughout the page, so I assigned it to a global variable. I have been under the impression that globals are bad. How else would I accomplish this?

Thanks

Edit: getGroups() is an API call. I don't want to have to call it multiple times.

Upvotes: 0

Views: 73

Answers (4)

Emmanuel Lozoya
Emmanuel Lozoya

Reputation: 136

Maybe you can have just one global variable, then you can access data through its public interface.

Example:

var myLibrary;

(function (lib) {
    var groups;
    function findGroups() {
        getGroups().then(function (g) {
            groups = g;
        });
    }
    function getLocalGroups() {
        return groups;
    }

    //public interface
    lib.findGroups = findGroups;
    lib.getLocalGroups = getLocalGroups;
}(myLibrary));

Upvotes: 0

Jonathan.Brink
Jonathan.Brink

Reputation: 25373

If you need to access that variable accross multiple pages establishing a global namespace could be a good way to go:

// file1.js (loaded first)
myApp = {}; // global namespace
(function() {
    var groups = {};

    myApp.findGroups = function() {
      return groups;
    };

    // init groups
    (function init() {
        getGroups().then(function (g) {
            groups = g;
        });
    }());
}());

// file2.js (loaded next)
myApp.findGroups(); // now myApp.groups is available

Upvotes: 1

Dzenly
Dzenly

Reputation: 1841

Or you can use OOP style:

var Group = {
    groups: null,
    findGroups: function() {
        getGroups().then(function (g) {
            Group.groups = g;
        });
    },
    fetchGroup: function(index){
        return Group.groups[index];
    }

};

Group.findGroups();
var group = Group.fetchGroup(index);

Or with constructor:

function Group(){
    this.groups = null;
    var self = this;
    this.findGroups = function() {
      getGroups().then(function (g) {
        self.groups = g;
      });
   };
};

var group = new Group();
group.findGroups();

Upvotes: 0

You can get the function in a closure, so the groups variable will be local:

(function(){
    var groups;

    function findGroups {
      getGroups().then(function (g) {
        groups = g;
      });
    }
})();

Upvotes: 1

Related Questions