0

I have an app running on Backbone in front-end and when a browser loads a page it returns an error in the console:

Uncaught ReferenceError: app is not defined
    at index.js:6
    at index.js:51
(anonymous) @ index.js:6
(anonymous) @ index.js:51

index.js

/* global app:true */

(function() {
  'use strict';

  app = app || {};  // error here although it must prevent of undefined 
                    // variables stay undefined

  //.......
  //backbone code here
  //.......

  $(document).ready(function() {
    app.contactView = new app.ContactView(); //error here
  });
}());

Switching from build to CDN or enter into a Backbone.Model properties returns the same error.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
ASem
  • 142
  • 3
  • 16

1 Answers1

3

Only move the variable outside of the function scope if you want it to be global.

/* global app:true */

var app = app || {};

(function() {
  'use strict';

  //.......
  //backbone code here
  //.......

  // you can use the jQuery shortcut version of the document ready.
  $(function() {
    app.contactView = new app.ContactView();
  });
}());

Or pass it as a parameter of the IIFE.

(function(app) {
  // ...
})(app = app || {});

If you have multiple files, they should all implement a similar structure as the examples above to be able to use the app namespace.

Additional information on namespacing

Community
  • 1
  • 1
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • No, these 2 options returned the same error. I have some more files with similar structure, maybe I should change them because it won't be global otherwise? – ASem Feb 24 '17 at 19:03
  • @ASem Each file should have the `var app = app || {};` line at the top. – Emile Bergeron Feb 24 '17 at 19:13
  • Changed them all and it helped, thanks! As I understand your first option leaves the global app object accessable but its properties are inside a function scope and it's safe to leave like so. – ASem Feb 24 '17 at 19:42
  • @ASem in fact, everything inside `app` is globally accessible since `app` is a global. The function scope let you define local variables that won't leak into the global space. This is useful for private parts of a component, simulating static field for a *class*, etc. – Emile Bergeron Feb 24 '17 at 19:58