2

This is another question on avoiding the global namespace.

For the web application I'm working on during my private time, I need a lot of objects instances that are shared between different modules. It is a single page application where almost all views are basically connected to each other (MVC perspective).

I namespaced my application as follows:

window.app = {
    views : {}, 
    models: {}, 
    collections: {}, 
    functions: {}
};

An illustration for a collection: Bar profile information can be represented as markers on a map, or as items in a list, or as information that is displayed on a profile, etc... So what I do is create an instance of the "bars_Collection", and add it to the app object in this fashion:

app.collections.bars_Collection = New Bar_Collection(); 

Fetching the data once makes the collection data available throughout the entire application.

Another illustration for a view:
I have a view object with a list of tags (keywords) that is updated, according to the Collection that it's being fed (cross-category -> can be bars, restaurants, etc...). So I would have single view for the tags that I add to the app object as follows:

app.views.tags_View = new Tags_View(); 

Although I am not really afraid of name collisions, I do realize that my app object resides in the Global namespace. I am concerned about the performance of the application, when adding more nested objects to the global app object: Why are global variables considered bad practice?

It is terribly handy though, to have these instances (app.views, app.models, etc.) within immediate reach all the time.

My question is: how do you assess this situation, and if you consider this bad practice, can you give me a practical pointer on what would be the better way?

Community
  • 1
  • 1
html_programmer
  • 18,126
  • 18
  • 85
  • 158
  • 2
    *Polluting* the global scope is bad (i.e. defining *many* global variables). Having a single variable in global scope, the root of your namespace, is perfectly fine. – Felix Kling Jan 31 '14 at 10:08
  • 1
    This is good practice, I don't think it makes a difference in performance. – elclanrs Jan 31 '14 at 10:09
  • Have you heard/read of closures, or in your case specifically IIFEs, before? – Boldewyn Jan 31 '14 at 10:09
  • @Boldewyn I read about how using closures helps avoiding functions to reside in the global namespace. Despite, I couldn't figure out how to use them to create a shared instance of an object throughout the application. If you would have some example code on how I can improve the code I provided above with IIFE's, I would be very interested. – html_programmer Jan 31 '14 at 10:14

0 Answers0