concept receiver in category coffeescript

appears as: receiver, receiver
CoffeeScript in Action

This is an excerpt from Manning's book CoffeeScript in Action.

connectJackNumber = (number) ->
  "Connecting jack #{number}"

receiver = 'Betty'

switch receiver
  when 'Betty'
    connectJackNumber 4
  when 'Sandra'
    connectJackNumber 22
  when 'Toby'
    connectJackNumber 9
  else
    'I am sorry, your call cannot be connected'

# 'Connecting jack 4'

Every time a function is invoked, some object is the receiver for that function invocation. In many cases, the receiver is unimportant to you, but when you’re handling an event, the object that’s receiving the event is important. When a function is handling a click event on an element in an HTML document, then the receiver is the element that was clicked, as shown in figure 4.4.

Figure 4.4. The receiver of a click event

Inside the handling function, the receiver is available using the @ symbol or the this keyword. It can be helpful to think of @ in terms of the object you are at or this in terms of this object that is being used, right now.

Using the receiver, you can now rewrite the duplicated event handlers so that instead of having two handlers you can have just one. First, rewrite one event handler to use the receiver. Instead of this