Reputation: 652
In the following code, I was under the impression that using a 'fat arrow' would allow me access to the class variables. Instead, regardless of fat or skinny arrow, I am not able to access the '@accounts' variable.
Any suggestions?
class MyClass
accounts:[]
constructor: (@accounts) ->
($ '.the_buttons').live 'click', bind_clicks
bind_clicks = (event) ->
console.log @accounts
jQuery ->
m = new MyClass([1, 2, 3])
Thanks.
Update
Looks like I had mistyped previously causing a bit of my problem.
Here is code that sort-of does the trick
class MyClass
accounts:[]
constructor: (@accounts) ->
($ '.the_buttons').live 'click', (event) => bind_clicks(event)
bind_clicks: (event) =>
console.log @accounts
jQuery ->
m = new MyClass([1, 2, 3])
However, it feels odd to resort to making the bind_clicks a public method.
Upvotes: 4
Views: 1713
Reputation: 4814
You can do that
class MyClass
bind_clicks = (event) ->
console.log @accounts
accounts:null
constructor: (@accounts) ->
($ '.the_buttons').live 'click', bind_clicks
jQuery ->
m = new MyClass([1, 2, 3])
bind_clicks is declared BEFORE the instance methods. It is private. BUT, it is a private class method. It will generate a closure, that's why. I would suggest to use _bind_clicks, the underscore prefix is a common convention to define private methods. Since this doesn't really exist in javascript.
Be careful also when you declare accounts:[], I would suggest accounts:null, more on this: http://html5stars.com/?p=148
Upvotes: 1
Reputation: 1546
You can try this out: http://jsfiddle.net/zp6LJ/1/
The private method will have to be defined int he constructor function to achieve what you are looking for.
class MyClass
accounts:[]
constructor: (@accounts) ->
bind_clicks = (event) =>
console.log @accounts
$('.the_buttons').click bind_clicks
jQuery ->
m = new MyClass([1, 2, 3])
Upvotes: 0
Reputation: 146
You can make bind_clicks private as follows:
class MyClass
accounts:[]
constructor: (@accounts, @button) ->
bind_clicks = (event) =>
console.log @accounts
@button.click bind_clicks
class Button
click: (@f) ->
do_click: -> @f('event')
button = new Button()
m = new MyClass([1, 2, 3], button)
console.log m.bind_clicks # undefined (private)
button.do_click() # [1, 2, 3]
Upvotes: 0
Reputation: 4771
Another possible way of doing this. It's pretty similar to yours.
class MyClass
constructor: (@accounts) ->
$('body').live 'click', @bind_clicks
bind_clicks: (event) =>
console.log @accounts
$ ->
m = new MyClass([1, 2, 3])
Don't quote me on this, but I don't think JS has any notion of public/private methods. I supposed if you don't want to expose the method you could do this instead. But you might run the risk or repeating yourself if you use this method more than once.
class MyClass
constructor: (@accounts) ->
$('body').live 'click', (event) =>
console.log @accounts
$ ->
m = new MyClass([1, 2, 3])
Good luck! Sandro
note: I bounded the events from the body so I could test out the code.
Upvotes: 0