2

I am having troubles trying to figure out why this code does not run. I get no error in the console at all.

const remove = saClass => {
  document.getElementsByClassName('site-alert')[0].remove();
};

const sitealert = ({message = 'Default message', dismissText = 'Close', className = 'site-alert'}) => {
  render(`<div id="sitealert" class="${className}">${message}<button id='close-message'>${dismissText}</button><div>`);
  document.getElementById('close-message').addEventListener('click', remove(className), false);
};

export const init = (options) => sitealert(options);

When i add a parameter remove(className) to the addEventListener the code does not run at all and I get no error in the console.

If I remove the parameter it all works fine.

Am i passing a variable incorrectly?

I should note that I am using babel to convert the code into a UMD format.

Thanks, Dave

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
davidjh
  • 387
  • 1
  • 7
  • 13
  • This question has been answered at least a thousand times. – Silom Jun 28 '16 at 13:41
  • 1
    Possible duplicate of [How to pass arguments to addEventListener listener function?](http://stackoverflow.com/questions/256754/how-to-pass-arguments-to-addeventlistener-listener-function) – Silom Jun 28 '16 at 13:42

4 Answers4

2

You can use a closure to pass in the variable and then return the actual callback:

const sitealert = ({message = 'Default message', dismissText = 'Close', className = 'site-alert'}) => {
  render(`<div id="sitealert" class="${className}">${message}<button id='close-message'>${dismissText}</button><div>`);
  document.getElementById('close-message').addEventListener('click', remove(className), false);
};

function remove(yourVar) {
    return function (e) {
        //yourVar is available here
    }
}
bcr
  • 3,791
  • 18
  • 28
0

An expression like

functionName(expression)

is a call to the function. What you want is another function. You can do that explicitly:

() => remove(className)

or with .bind():

remove.bind(null, className)
Pointy
  • 405,095
  • 59
  • 585
  • 614
0

The second argument of addEventListener needs to be a function.

remove is a function.

remove(className) is the result of calling that function with an argument. Since the function has no return statement, that result is undefined.

If you want to generate a function that will call remove with an argument, use bind.

remove.bind(null, className)
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

If you have a fonction with parameters, you should use:

.addEventListener('onclick', function() {remove(className)}, true);

in order to specify its a function

Gaetan
  • 325
  • 1
  • 15