I'm trying to access a variable from a namespace on the same page at a "global" level but thus far have been unable to do so. Here's the code:
window.addEventListener('resize',
() => {
alert('entityId in addEventListener alert: ' + Best.Namespace.Ever.entityId);
// prints "entityId in addEventListener alert: undefined"
});
var Best = Best || {};
Best.Namespace = Best.Namespace || {};
Best.Namespace.Ever= Best.Namespace.Ever || (function () {
var entityId;
function doSomethingAmazing(something) {
entityId = alterEntityIdBasedUponSomething(something);
alert('entityId in doSomethingAmazing: ' + entityId);
// prints "entityId in doSomethingAmazingalert: 14"
// a lot of other stuff
}
return {
doSomethingAmazing: doSomethingAmazing,
entityId: entityId
// a lot of other stuff
};
}());
The issue here is that I'm unable to access the entityId from within the alert in the addEventListener method. At that point it is undefined. However, I can access it in the alert just after it is set just fine. (See the comments in the code above for what prints.)
I feel like this should be possible and I just don't know the correct way to access entityId. If anyone has any ideas I would very much appreciate it.
Thanks!!
As it turns out this wasn't exactly an issue with the code, but rather with unexpected page loading/event firing. What was happening is that the doSomethingAmazing
function was being called on page load and was setting the entityId
to 14 just fine. However, after that another event (or something) was reloading the entire script again which was re-initializing entityId
back to undefined (but NOT calling doSomethingAmazing). So when the resize event was called and entityId
was printed it was undefined.
My problem here was a failure to understand the basic principle that the entityId
is essentially stateless between JavaScript page loads; it gets re-initialized every time the entire script is loaded.
Hopefully this helps someone!