Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Coffeescript 'this' from within jQuery $.bind()?

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!

like image 338
jlstr Avatar asked Dec 28 '11 16:12

jlstr


People also ask

What is bind() in jQuery?

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.


1 Answers

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!'
like image 122
Sandro Avatar answered Oct 11 '22 12:10

Sandro