可以't访问文件外的coffeescript函数

Can't access coffeescript function outside of file

本文关键字:coffeescript 函数 文件 访问 可以      更新时间:2023-09-26

我正在尝试设置一个服务来执行对远程服务器的json请求。

我在services.coffee脚本中使用以下代码:

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()

initialize方法工作正常。

我希望能够从项目中的任何位置访问变量http

但是,我无法访问此文件之外的函数。

我如何在全球范围内定义它?

更新

这是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);

这是因为coffeescript将代码包装在顶级函数安全包装器中。

在浏览器中,您可以通过以下操作使其全球化:

window.http = http

或者告诉coffeescript不要用-b:编译包装器

coffee -c -b services.coffee

一般来说,全局变量不是一个好主意,您可能需要考虑使用require.js这样的模块系统来组织和访问代码(包括不同文件中的代码)。

这将使变量在浏览器的上下文中全局化:

window.http = http