0

I am writing an app in CoffeeScript where the main object is declared as this:

App =
  Models: {}
  Views: {}
  Collections: {}
  start: ->
    console.log('started')
    null

require ['models/question', 'views/question'], ->
  new App().start()
  null

This code compiles to javascript like this:

(function() {
  var App;
  App = {
    Models: {},
    Views: {},
    Collections: {},
    start: function() {
      console.log('started');
      return null;
    }
  };

  require(['models/question', 'views/question'], function() {
    new App().start();
    return null;
  });

}).call(this);

In the model code "required" in this program, the Coffeescript and its compilation look like this:

#Coffeescript
    App.Model.Question = Backbone.Model.extend(
      defaults : ->
        question: "How're you"
    )


//Javascript

(function() {
  App.Model.Question = Backbone.Model.extend({
    defaults: function() {
      return {
        question: "How're you"
      };
    }
  });

}).call(this);

Because of the way that coffeescript compiles there are no global variables in the compiled code. So when the Question model page loads it throws an error: in the browser console:

Uncaught ReferenceError: App is not defined

I am not sure how to work around this, because I will have LOTS of references across modules in my project. How can I ensure visibility across modules - while working with coffeescript.

EternallyCurious
  • 2,345
  • 7
  • 47
  • 78

2 Answers2

0

"Compile the JavaScript without the top-level function safety wrapper" by passing the -b or --bare flag to the compiler. See Usage section of documentation

maxbeatty
  • 9,050
  • 3
  • 33
  • 36
0

You can set it as global or "namespaced" by simply putting it there.

window.MyNamespace = {}
window.MyNamespace.App = App
NeutronCode
  • 365
  • 2
  • 13