Reputation: 878
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
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
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
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
Reputation: 2974
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