Justin D.
Justin D.

Reputation: 4976

Can't access coffeescript function outside of file

I am trying to set up a service to perform json requests to a remote server.

I am using this code inside my services.coffee script :

HttpService = () ->

  initialize: -> 
    __Model.List.destroyAll()
    __Model.Item.destroyAll()

    $$.get 'http://localhost:3000/lists.json', null, ((response) ->
      lists = response.lists
      items = response.items

      $$.each lists, (i, list) ->
        __Model.List.create list

      $$.each items, (i, item) ->
        __Model.Item.create item
    ), 'json'

  createList: (list) ->
    $$.post 'http://localhost:3000/lists.json', list, ((response) ->
      ), 'json'

http = new HttpService
http.initialize()

The initialize methods works fine.

What I would like is to be able to access the variable http from anywhere in my project.

However, I cannot access the function outside this file.

How can I define it globally?

UPDATE

Here is the file generated by CoffeeScript

// Generated by CoffeeScript 1.6.3
(function() {
  var HttpService, http;

  HttpService = function() {
    return {
      initialize: function() {
        __Model.List.destroyAll();
        __Model.Item.destroyAll();
        return $$.get('http://localhost:3000/lists.json', null, (function(response) {
          var items, lists;
          lists = response.lists;
          items = response.items;
          $$.each(lists, function(i, list) {
            return __Model.List.create(list);
          });
          return $$.each(items, function(i, item) {
            return __Model.Item.create(item);
          });
        }), 'json');
      },
      createList: function(list) {
        return $$.post('http://localhost:3000/lists.json', list, (function(response) {}), 'json');
      }
    };
  };

  http = new HttpService;

  http.initialize();

}).call(this);

Upvotes: 2

Views: 479

Answers (2)

go-oleg
go-oleg

Reputation: 19480

That is because coffeescript wraps the code in a top-level function safety wrapper.

In a browser, you can make it global by doing:

window.http = http

or tell coffeescript to not do the wrapper by compiling with -b:

coffee -c -b services.coffee

In general, global variables aren't a very good idea and you may want to consider using a module system like require.js to organize and access your code (including code in different files).

Upvotes: 4

Matthew Graves
Matthew Graves

Reputation: 3294

This will make the variable global in the context of the browser:

window.http = http

Upvotes: 3

Related Questions