1

In C, if I don't dynamically malloc Anything inside a function, it is free'd when the function ends. I have no clue how Javascript (in special, event listeners) works in that sense. The question is, if a event listener is declared inside a function, is it killed when the function ends or it keeps listening?


CONTEXT

I have an object page{} with a method battle().

In a choose_action() method from page, I call battle().

When battle() ends, choose_action is called again.

Battle() have event.listeners addressed to buttons with fixed ids ("attack", "defense", etc). When the img with the id "attack" is pressed, the attack()(Which is also a page{} method) function is called.

My point is, are the event.listeners created in battle() global? Or are they freed when battle() ends? I'm afraid calling battle() again will create doubled attack_event_listeners, that will make attack (n) times every click, n being the times battle() is called.

A.A Noman
  • 5,244
  • 9
  • 24
  • 46
abcson
  • 157
  • 9
  • 1
    Please don't only explain your code, show it! – Teemu Apr 30 '19 at 05:25
  • 1
    @Teemu I don't have the code at all. That's what i plan do code, i want to know if this works before trying to – abcson Apr 30 '19 at 05:25
  • Since i would spend 4+ hours to properly implement all of this. – abcson Apr 30 '19 at 05:26
  • You'd already know, if you'd tried ... – Teemu Apr 30 '19 at 05:26
  • If i discover it fails, i will have spent hours and won't know how to solve my problem. I'm just giving context. What i want to know is if event listeners called in a function are freed when the function ends. – abcson Apr 30 '19 at 05:27
  • It's not a hard question to answer if you know the answer. In c, which i know a little bit, it's easy to answer. If you don't dynamically storage anything you declare on a function, it dies with the function. But c's not javascript, i have no clue how it deals with this kind of thing. – abcson Apr 30 '19 at 05:29
  • No, the event listener function is not killed after the attaching function/method has been executed, and the element the event was attached to, continues to listen the event, and when it fires, it executes the attached event handler. – Teemu Apr 30 '19 at 05:36
  • Can i force the event listener to be local? – abcson Apr 30 '19 at 05:37
  • It doesn't help, this is more related to closures and how the automatic garbage collection works. See https://stackoverflow.com/questions/111102/how-do-javascript-closures-work?r=SearchResults&s=1|3912.0120 – Teemu Apr 30 '19 at 05:38
  • 2
    You can use `removeEventListener` (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener) at the end of the battle, which should resolve your concern. – Cat Apr 30 '19 at 05:41

0 Answers0