[英]Can't read CoffeeScript global variable
I have two coffeescript files, the first have these lines: 我有两个coffeescript文件,第一个有以下几行:
jQuery(document).ready ($) ->
dispatcher.bind "createuserchannel", (channelid) ->
root = (exports ? this)
root.channel_user = dispatcher.subscribe(channelid)
and the latter these: 后者是:
jQuery(document).ready ($) ->
root = (exports ? this)
console.log root.channel_user
I don't know why but in the Chrome console when i write Object.keys(window)
the channel_user
appears as a global variable but if i try to access it from Javascript only gets Undefined 我不知道为什么,但是在Chrome控制台中,当我编写
Object.keys(window)
, channel_user
显示为全局变量,但是如果我尝试从Javascript访问它,则只会得到未定义
Inside callbacks to jQuery events (such as your second case), jQuery sets this
to the object that fired the event (in this case, document
). 在jQuery事件的回调(例如第二种情况)中,jQuery
this
设置为触发事件的对象(在本例中为document
)。 You have two options that I see: 您看到两个选择:
First, you could explicitly use window
. 首先,您可以显式使用
window
。 Its not clear whether this would fit your use-case. 目前尚不清楚这是否适合您的用例。
root = (exports ? window)
Second, you could use the CoffeeScript fat arrow to retain the this
from the outer scope. 其次,您可以使用CoffeeScript粗箭头从外部范围保留
this
箭头。 Note that if you're depending on the other this
behavior anywhere else in that function, this will cause trouble. 请注意,如果您在该函数中的其他任何地方都依赖
this
行为,则会造成麻烦。
jQuery(document).ready ($) =>
I would assume the same is going on in your second case, but without knowing exactly what dispatcher
is, its impossible to know for sure. 我想在第二种情况下也会发生同样的情况,但是如果不确切知道
dispatcher
是什么,就不可能确定。
Solved: 解决了:
The dispatcher.bind
is an asynchronous function so at the time I access the variable from this function: dispatcher.bind
是一个异步函数,因此在我从该函数访问变量时:
jQuery(document).ready ($) ->
root = (exports ? this)
console.log root.channel_user
channel_user is still not assigned. channel_user仍未分配。 To solve the problem i've added this line:
为了解决该问题,我添加了以下行:
jQuery(document).ready ($) ->
dispatcher.bind "createuserchannel", () ->
root = (exports ? this)
console.log root.channel_user
In this way root.channel_user
will be called only when channel_user
has been setted. 这样,仅当设置了
channel_user
时,才会调用root.channel_user
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.