Search code examples
javascriptnamespaceswindowglobal-variablesglobalization

Cannot set property of undefined - Global objects and namespacing in JavaScript


I'm using a variable attached to the window:

window.App

As a reference point for the rest of my variables within my application. However, when I attempt to do this:

window.App = {};

App.Views.User.Login = /* Login View Instance */;

It will complain about Views not being defined. This is fine for the most part because I can predefine App.Views, App.Models, App.Collections, etc.

However when we get into the submodules that aren't always needed (App.Views.User) I would prefer for this to be loaded when needed...

Is the only option the following?

if( ! App.Views.User ) { App.Views.User = {}; };

App.Views.User.Login = /* Login View Instance */;

Solution

  • I would start your submodules like this:

    App.Views.User = App.Views.User || {};
    App.Views.User.Login = new Backbone.Marionette.ItemView.extend({});
    

    Only marginally cleaner than what you have already but that's generally what you do.