Override a function already attached to an event

Viewed 55

I want to override a function already attached to an event. Like that :

let orFn = () => {
  console.log('old');
};

buttonEl.addEventListener('click', orFn);

orFn = () => {
  console.log('new');
};

However, when I click on the button, the old function is still called. I have seen this stackoverflow. I can't use a function wrapper in my case. And I want to understand why this is not working.

My code is available for testing here: jsfiddle.

2 Answers

One way is to remove first listener, then add another one

let orFn = () => {
  console.log('old');
};

let orFnNew = () => {
  console.log('new');
};

var buttonEl = document.querySelector('button')

buttonEl.addEventListener('click', orFn);

// remove old listener
buttonEl.removeEventListener('click', orFn);

// add another one
buttonEl.addEventListener('click', orFnNew);
<button>button</button>

Another way is to have one listener, that may call different functions inside. Example:

// button
const buttonEl = document.querySelector('button')

const orFn = () => {
  console.log('old');
};

const orFnNew = () => {
  console.log('new');
};

// function that will be called
let functionToCall = orFn;

buttonEl.addEventListener('click', (event) => { // single listener
  
  functionToCall.call(event); // call a function with event


  functionToCall = functionToCall === orFn ? orFnNew : orFn; // change function to be called
});
<button>button</button>

One way of using bind().

const btn = document.getElementById('btn');

let orFn = () => {
  alert('old');
};

orFn = () => {
  alert('new');
};

orFn.bind(orFn)

btn.addEventListener('click', orFn);

This will bind with new function and show new in alert Popup.

Related