[英]Can't access coffeescript function outside of file
I am trying to set up a service to perform json requests to a remote server. 我正在尝试设置服务以执行对远程服务器的json请求。
I am using this code inside my services.coffee
script : 我在
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()
The initialize methods works fine. 初始化方法工作正常。
What I would like is to be able to access the variable http
from anywhere in my project. 我想要的是能够从项目中的任何位置访问变量
http
。
However, I cannot access the function outside this file. 但是,我无法访问此文件之外的功能。
How can I define it globally? 如何全局定义?
UPDATE UPDATE
Here is the file generated by CoffeeScript 这是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);
That is because coffeescript wraps the code in a top-level function safety wrapper . 这是因为coffeescript将代码包装在顶级函数安全包装器中 。
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
: 或者告诉coffeescript不要用
-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). 通常,全局变量不是一个好主意,您可能需要考虑使用像require.js这样的模块系统来组织和访问您的代码(包括不同文件中的代码)。
这将使变量在浏览器的上下文中成为全局变量:
window.http = http
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.