I have two coffeescript files, the first have these lines:

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

有帮助吗?

解决方案 2

Solved:

The dispatcher.bind is an asynchronous function so at the time I access the variable from this function:

jQuery(document).ready ($) ->
 root = (exports ? this)
 console.log root.channel_user

channel_user is still not assigned. 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.

其他提示

Inside callbacks to jQuery events (such as your second case), jQuery sets this to the object that fired the event (in this case, document). You have two options that I see:

First, you could explicitly use 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. Note that if you're depending on the other this behavior anywhere else in that function, this will cause trouble.

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top