在流星0.6.4.1/coffeescript中,变量可见性如何工作?

Jer*_*rry 8 coffeescript meteor

我是meteor和coffeescript的新手.我正在使用非官方流星常见问题解答中建议的文件布局.在文件集/ C.coffee中,我有

C = new Meteor.Collection 'C'
console.log "C: #{C}"
Run Code Online (Sandbox Code Playgroud)

在文件服务器/ main.coffee中,我有

C.insert {test: 'test'}
Run Code Online (Sandbox Code Playgroud)

当我启动流星时,我在控制台上看到:

C: [object Object]
ReferenceError: C is not defined
    at app/server/main.coffee.js:5:1
    at /home/xxx/yyy/.meteor/local/build/server/server.js:298:12
Run Code Online (Sandbox Code Playgroud)

如何在collections/C.coffee之外的文件中提供C?

更新:添加@到C修复了顶级问题.但它仍然失败:

   Meteor.methods
        test: (statement) ->
             @C.insert {test: 'test'}
Run Code Online (Sandbox Code Playgroud)

它失败并出现错误 TypeError: Cannot call method 'insert' of undefined

Aks*_*hat 13

为了使C在文件外可见,它在使用中定义@,编译到js this.window.在js中,这使它具有与全局范围相同的效果:

@C = new Meteor.Collection 'C'
Run Code Online (Sandbox Code Playgroud)

  • 在服务器端,`@`在顶级上下文中等于`global`.但是你不需要使用`global.C`来访问它; 你可以做`C`. (2认同)