66
Views
3
Comments
remove addEventListener from the DOM

Here I add eventlistner, where i add click event for the button. When i click the button it will redirect to another page.

In this case do i need to remove eventlistner manually from the DOM. 

or as we are redircting to the another page it will take care by the platform itself.

EventListner - will keep the event running even when go to another page. 

What is the best approach, should i remove it from the DOM manually on OnDestroy?


2021-09-06 15-09-53
Dorine Boudry
 
MVP

yes, remove eventListeners in the OnDestroy

but, more importantly, don't do in Javascript what you can do in the OutSystems code.  If you want an action to run when a button is clicked, you can already do that in OutSystems, no need for Javascript.

Dorine

2019-01-07 16-04-16
Siya
 
MVP

General Syntax of addEventListener

document.addEventListener(type, listener [, options]);

If you set the option { once: true }, the listener is automatically removed after being triggered once. For example:

btn.addEventListener("click", handleClick, { once: true });

However, if the "click" event never occurs, the event listener will not be removed, potentially leading to memory issues. To avoid this, you should explicitly remove the event listener in OnDestroy.

Suggested Implementation

  1. Define a Local Variable ( of type Object)  to Store the Event Handler: Assign a JavaScript function to $parameters.Handler in OnReady:

    $parameters.Handler = function handleClick() {    console.log("Button clicked!");    $actions.VirtualBtnClick(); };

  2. Manage Event Listeners in EventListenerOnClick:

    • Remove any existing event listener before adding a new one.
    • Add the event listener with { once: true } to ensure it executes only once:
      var btn = document.getElementById($parameters.ButtonId); btn.removeEventListener("click", $parameters.Handler); btn.addEventListener("click", $parameters.Handler, { once: true });
  3. Clean Up in OnDestroy: Explicitly remove the event listener to ensure there are no memory leaks:

    var btn = document.getElementById($parameters.ButtonId); btn.removeEventListener("click", $parameters.Handler);


Note : To remove a listener, JavaScript requires the exact same function reference used in addEventListener. If the reference is different, removeEventListener will silently fail and the listener won't be removed. Hence the function reference is kept in the $parameters.Handler and used in add and remove event handlers. 

2023-02-19 05-11-08
Faais

Hi pradip, 

For in this case, you don't need to do anything in OnDestroy. If there are any active processes or tasks, you might need to clean up the dom. However, for simple navigation actions, it's completely fine to leave onDestroy empty

Community GuidelinesBe kind and respectful, give credit to the original source of content, and search for duplicates before posting.