macsig macsig - 3 years ago 256
CoffeeScript Question

removing event listener after firing it up

I have the following HTML

<button id="btn" type="button">Click Me!</button>
<div id="outside">
<div id='inside" class="animated">

When I click the button I first show the
and then animate the
. That works just fine.

When I click again, I first animate back the
and then hide the
. To do so I add an event listener to the
div, to listen for
. It works fine the first time. However, the second time I try to hide the
the listener is fired up and it does not work properly. Now, I'm trying to remove the event listener right after it is fired up the first time but I cannot make it work.

Here my last attempt.

hideOutside: =>
@inside.addEventListener 'animationend', @handler(event), no

handler: (e) =>
@sheet.removeEventListener @animationEvent, @handler(event), no

I have seen sample on SO similar to mine and I don't understand what is wrong with mine.

Thanks (please do not remove this).

Answer Source


@inside.addEventListener 'animationend', @handler(event), no
# ---------------------------------------^^^^^^^^^^^^^^^

doesn't do what you think it does. That's actually calling @handler, not passing a reference to it so it is the same as saying:

x = @handler(event)
@inside.addEventListener 'animationend', x, no

so @handler(event) is being called before addEventListener.

You want to work with the function reference so:

@inside.addEventListener 'animationend', @handler, no


@sheet.removeEventListener @animationEvent, @handler, no
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download