When using classes in Coffeescript, I've stumbled upon a major problem, let me illustrate
class Bet
constructor: () ->
placeBet: ->
$('#chips > div').bind 'click', ->
amount = $(this).attr 'id'
pile = $(this)
switch amount
when "ten" then this.bet pile, amount #This line causes a problem
bet: (pile, amount) ->
alert 'betting!'
The call to this.bet above generates the following error:
Uncaught TypeError: Object # has no method 'bet'
So, currently the instance method of my class is not being called, How can I correctly call the bet method of my class without it colliding with the jQuery selector's this (Which is what I suppose is happening now)?
Thank you very much in advance!
The bind() is an inbuilt method in jQuery which is used to attach one or more event handlers for selected element and this method specifies a function to run when event occurs.
Another solution is to use the CoffeeScript fat-arrow in the click event handler then your scope would be the same as if you were inside the placeBet function. You would then use e.currentTarget
to get a reference to the target object instead of using $(this)
class Bet
constructor: ->
placeBet: ->
$('#chips > div').bind 'click', (e) =>
target = $(e.currentTarget)
amount = target.attr 'id'
switch amount
when "ten" then @bet target, amount #This line causes a problem
bet: (pile, amount) ->
alert 'betting!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With