Search code examples
javascriptfetchbind

Native javascript: How to skip rebinding eventlisteners after fetch()?


I've started to use native javascript few months ago. When I use fetch(), I have to rebind eventlisteners (click, change, etc). Can I skip this to shorten the code?

I use for example: document.getElementById("click", function)
And I have to repeat them after every ajax call.

Update: example code

document.addEventListener("DOMContentLoaded", function(){
 document.getElementById("another_button").addEventListener("click", antoher_function);
document.getElementById("another_button2").addEventListener("click", antoher_function2);
document.getElementById("another_button3").addEventListener("click", antoher_function3);
//just a fetch call for example
fetch(url, {method: 'POST',
body: data
})
.then(respone => response.json())
.then(json => {
//HERE IS MY PROBLEM, I have to add another buttons event listeners, to work again
document.getElementById("another_button").addEventListener("click", antoher_function);
document.getElementById("another_button2").addEventListener("click", antoher_function2);
document.getElementById("another_button3").addEventListener("click", antoher_function3);
});
})

Solution

  • Yes: you can add a single event listener one time to the document root. The event will bubble up to the root, where you can check if the actual target is one of the buttons you wanted. For example:

    document.addEventListener("click", function(event) {
      switch (event.target.id) {
        case "another_button": another_function(); break;
        case "another_button2": another_function2(); break;
        case "another_button3": another_function3(); break;
      }
    });
    

    You might want to use class instead of id to identify the buttons, and maybe some data attributes to pass parameters. That depends on your particular case though.