0

I am a newbie in Coffeescript and would like to use the delegate() method in jquery 1.6.4. The method signature is .delegate( selector, eventType, handler ). How do I go about calling this method in Coffeescript? I am using Rails 3.1.

Thanks, Dany.

codedog
  • 2,488
  • 9
  • 38
  • 67

4 Answers4

6

just like any other method in coffeescript?

($ 'body').delegate '.external.link', 'click', (evt) ->
  # handler body

i feel like i'm missing something about your question...

just somebody
  • 18,602
  • 6
  • 51
  • 60
  • Many thanks, it seems amazingly obvious now that you've said it. However, what happens if there are two handlers in the parameters? – codedog Nov 13 '11 at 10:59
  • isn't the $sign on the wrong side of the parenthesis? – bobbdelsol May 05 '14 at 23:25
  • @bobbdelsol: no. `$ 'body'` is a coffeescript expressioon just like `$('body')` in javascript. `$ 'body'.delegate` in cs is *unlike* `$('body').delegate` in js, and parentheses reset operator precedence in both languages. `($ 'body').delegate` in cs is just like `($('body')).delegate` in js. – just somebody May 06 '14 at 21:40
3

To reply to your 2 handlers question:

$('body').hover ->
  # handler 1
  console.log 'in'
, ->
  # handler 2
  console.log 'out'

http://js2coffee.org/ is a good website to have in background if you write coffeescript without an automatic compiler that allows you to check imediatly the resulting javascript.

Guillaume86
  • 14,341
  • 4
  • 53
  • 53
1

It's a pure matter of aesthetics, but I prefer to wrap my handlers in named functions (if there's more than one):

    over = => ...
    out  = => ...

    $el.hover over, out

It just seems cleaner for me.

Rafal Pastuszak
  • 3,100
  • 2
  • 29
  • 31
1

I may be dense but the correct answer above took me some time to figure out. the first parameter is the div or ? that you want to watch for new elements, then you need to provide the element identifier , then the event type

$('#forum-senate-admin-lists').delegate 'input[id=delete-forum-object]','click', (evt) ->
    deleteForumObject($(this))`
bobbdelsol
  • 996
  • 6
  • 21