0

How can I get the code below to work? I'm trying to pass an argument to doAlert() without using an anonymous function.

var d = new Date();
var a = d.getTime();

e = document.getElementById('trigger')
e.addEventListener('click', doalert(a), false);

function doalert(a) {
    alert(a);
}

The below code works fine, but I cannot do it this way

e = document.getElementById('trigger')
e.addEventListener('click', function() {
    doalert(a)
});

HTML

<!DOCTYPE html>
<html>
<body>
<div id="trigger">Click to test</div>
</body>
</html>
Norman
  • 6,159
  • 23
  • 88
  • 141
  • 1
    `e.addEventListener('click', doAlert.bind(null, a), false);` – VLAZ Oct 18 '20 at 11:27
  • If you want to pass extra arguments to your event listener handler, you will always need an extra function ([even when you'd fork Function prototype](https://stackoverflow.com/a/39354642/1169519)). So, technically, using an anonymous function is just as good as any other concept here. – Teemu Oct 18 '20 at 11:32
  • I would either use the solution @VLAZ suggested, or use an arrow function: e.addEventListener('click', ()=>doalert(a), false);. Anyway I just want to point out that your first snippet will actually invoke function as the JS interpreter will get to this line so don't use it whatsoever. – Tamir Nakar Oct 18 '20 at 12:06
  • Can this be done using apply? – Norman Oct 18 '20 at 12:22
  • Uh, if you do `Function.prototype.apply.bind(doAlert, null, [a])` for example. Of course the *more sane* alternative is `() => doAlert.apply(null, [a])` but even then that's 1. using an anonymous function 2. not really of any benefit over `() => doAlert(a)`. The bottom of the problem is that you need to give a function reference to `addEventListener` and an anonymous one is the simplest option. `.bind` can also be used as it performs partial application and produces a function. Anything else must wrap your call into a function. – VLAZ Oct 18 '20 at 12:33

0 Answers0