2013-07-17 42 views
2

我正在嘗試設置一個服務來執行json請求到遠程服務器。無法訪問文件外的coffeescript功能

我使用此代碼我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() 

初始化方法工作正常。

我希望能夠從我的項目中的任何地方訪問變量http

但是,我無法訪問此文件以外的功能。

如何在全球範圍內定義它?

UPDATE

下面是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); 
+0

該腳本在哪裏執行?您的coffescript編譯器是否將所有內容都包含在一個大的IEFE中? – Bergi

+0

目前正在執行所有其他操作。不過,我嘗試過之間執行它,但沒有成功。 –

+0

[CoffeeScript&Global Variables]的可能重複(http://stackoverflow.com/questions/4214731/coffeescript-global-variables) – Bergi

回答

3

生成的文件這將使可變全球瀏覽器的情況下:

window.http = http 
+0

謝謝!像魅力一樣工作!我會在8分鐘內將其標記爲接受的答案。 –

+0

8分鐘?這是奇怪的具體:) –

+0

SO以前不會讓我接受;-) –

4

這是因爲CoffeeScript的包裹代碼在top-level function safety wrapper

在瀏覽器中,你可以把它的全球做:

window.http = http

,或者告訴CoffeeScript中不與-b編譯做包裝:

coffee -c -b services.coffee

一般情況下,全局變量不是一個好主意,您可能需要考慮使用像require.js這樣的模塊系統來組織和訪問您的代碼(包括cod e在不同的文件中)。

+0

非常詳細的答案。謝謝! –