Hello,
Im adding an event with two handlers to the same container with the class "dropzone"
event is "keydown", and the two functions are
handleCopy() and handlePaste(),
i have set the two functions in the same javascirpt outsystems field, made a boolean input which will change depending on the status of adding or removing the listener, and implemented this code :
function addEventListenersToDropzone() {
const dropzone = document.querySelector('.dropzone');
dropzone.addEventListener('keydown', handleCopy);
dropzone.addEventListener('keydown', handlePaste);
}
function removeEventListenersFromDropzone() {
dropzone.removeEventListener('keydown', handleCopy);
dropzone.removeEventListener('keydown', handlePaste);
let Test = $parameters.In1;if (Test) {
console.log("event added");
addEventListenersToDropzone();
} else {
console.log("event deleted");
removeEventListenersFromDropzone();
what is happening next , when this code is executed, events are added succesfully, but when the input have False, i get the console.log event deleted text, but events are not deleted.
Any solution will be much appreciated.
Regards.
The only solution that i managed to obtain is the following ;
Since we are working in a React environment, the most reliable way to handle dynamic event listeners is to use React's state and lifecycle methods (or hooks) to manage these event listeners.
Direct DOM manipulation as i was trying to implement won't work, therefore the best solution is to sets customs attributes on html elements, in order to check if events is already added, active or inactive.
Can you try creating a global variable and make it true/false at the end of each functions.
In this we way you can handle whether the remove event is executed or not.
-Aravind.
Hii @Omar Abdelkefi,
There is some improvement required in your code
// Boolean flag to track event listener state
let eventListenersAdded = false;
// References to event listener functions
let handleCopyRef;
let handlePasteRef;
if (!eventListenersAdded) {
handleCopyRef = dropzone.addEventListener('keydown', handleCopy);
handlePasteRef = dropzone.addEventListener('keydown', handlePaste);
// Update flag to indicate event listeners are added
eventListenersAdded = true;
// Check if event listeners exist
if (eventListenersAdded) {
dropzone.removeEventListener('keydown', handleCopyRef);
dropzone.removeEventListener('keydown', handlePasteRef);
// Update flag to indicate event listeners are removed
eventListenersAdded = false;
let Test = $parameters.In1;
if (Test) {
This code ensures that the event listeners are only added once and removes them correctly when the flag changes. Additionally, it stores the references returned by addEventListener and uses them in removeEventListener to ensure accurate removal.
Hope this will solve your problem
kind regards,
Sanjay Kushwah
Omar Abdelkefi ,
Since the question is something related to Javascript, Same you can check in ChatGpt will tell u the same solution.