Alexander Popov
Alexander Popov

Reputation: 24875

How to access a variable across CoffeeScript functions?

I use CS in Rails. If I have:

foo = ->
  ...

bar = ->
  ...

-> 
  someCount = 123
  foo()
  bar()

How can I access someCount inside foo() and bar() without passing it directly as an argument?

I thought that this would require declaring someCount as a global variable. I read this and this, but I don't understand how to implement it. I tried:

root = exports ? this
root.someCount = 123

but then inside foo() I couldn't access it by either someCount (someCount is not defined) or root.someCount(root is not defined).

Upvotes: 0

Views: 63

Answers (1)

deceze
deceze

Reputation: 522016

You simply need to declare somecount in a scope that the other functions are also in:

somecount = null

foo = ->
  alert somecount

bar = ->
  alert somecount

-> 
  someCount = 123
  foo()
  bar()

Upvotes: 1

Related Questions