In meteor 0.6.4.1/coffeescript, how does variable visibility work?

牧云@^-^@ 提交于 2020-01-03 08:22:18

问题


I'm new to meteor and coffeescript. I'm using the file layout suggested in the Unofficial Meteor FAQ. In file collections/C.coffee, I have

C = new Meteor.Collection 'C'
console.log "C: #{C}"

In file server/main.coffee, I have

C.insert {test: 'test'}

When I start meteor, I see on the console:

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

How do I make C available in files outside of collections/C.coffee?

Update: Adding @ to C fixes the problem at the top level. However it still fails with:

   Meteor.methods
        test: (statement) ->
             @C.insert {test: 'test'}

It fails with an error TypeError: Cannot call method 'insert' of undefined


回答1:


To make C visible outside the file it was defined in use @, which compiles to this. or window. in js, which gives it the same effect as a global scope:

@C = new Meteor.Collection 'C'


来源:https://stackoverflow.com/questions/18150532/in-meteor-0-6-4-1-coffeescript-how-does-variable-visibility-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!