Events » Removing an event handler

Removing an event handler

How do you get rid of an event? What if you want a layer to stop listening to, say, a tap gesture?

You must have noticed that all the events start with ‘on’ (onTap, onDoubleTap…). This is because we’re activating an event on a layer, in other words, switching it ‘on’.

We’ve actually been using shortcuts. This:

layerA.onTap ->

Is short for this:

layerA.on Events.Tap, ->

In addition to layer.on there’s also a layer.off, for telling the layer to stop listening to an event.

To use layer.off you’ll have to put your function in a variable, so that you can tell the layer which function to not execute any longer.

# ‘tapHandler’ contains a function
tapHandler = ->
    redSquare.backgroundColor = "green"
# ‘tapHandler’ gets triggered on ‘Events.Tap’
redSquare.on Events.Tap, tapHandler
# ‘tapHandler’ ceases to trigger on ‘Events.Tap’
redSquare.off Events.Tap, tapHandler

Note that when you directly add a function (like tapHandler above), you don’t have to call the function. In other words, you don’t need to type tapHandler().

It’s a bit annoying, though, to have to make separate functions. You might opt instead to have your layer simply ignore events.