macsig macsig - 10 months ago 103
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">
</div>
</div>


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

When I click again, I first animate back the
inside
and then hide the
outside
. To do so I add an event listener to the
inside
div, to listen for
animationend
. It works fine the first time. However, the second time I try to hide the
outside
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
@outside.classList.remove('is-active')


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

This:

@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

and:

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