In the first line of your JS code:
select.addEventListener('change', getSelection(this), false);
you're invoking getSelection by placing (this)
behind the function reference. That is most likely not what you want, because you're now passing the return value of that call to addEventListener, instead of a reference to the actual function itself.
In a function invoked by addEventListener
the value for this
will automatically be set to the object the listener is attached to, productLineSelect
in this case.
If that is what you want, you can just pass the function reference and this
will in this example be select
in invocations from addEventListener:
select.addEventListener('change', getSelection, false);
If that is not what you want, you'd best bind
your value for this to the function you're passing to addEventListener
:
var thisArg = { custom: 'object' };
select.addEventListener('change', getSelection.bind(thisArg), false);
The .bind
part is also a call, but this call just returns the same function we're calling bind
on, with the value for this
inside that function scope fixed to thisArg
, effectively overriding the dynamic nature of this-binding.
To get to your actual question: "How to pass parameters to function in addEventListener?"
You would have to use an additional function definition:
var globalVar = 'global';
productLineSelect.addEventListener('change', function(event) {
var localVar = 'local';
getSelection(event, this, globalVar, localVar);
}, false);
Now we pass the event object, a reference to the value of this
inside the callback of addEventListener, a variable defined and initialised inside that callback, and a variable from outside the entire addEventListener call to your own getSelection
function.
We also might again have an object of our choice to be this
inside the outer callback:
var thisArg = { custom: 'object' };
var globalVar = 'global';
productLineSelect.addEventListener('change', function(event) {
var localVar = 'local';
getSelection(event, this, globalVar, localVar);
}.bind(thisArg), false);