I am facing a situation where I have an event handler that needs parameters and triggers a callback function using window.setTimeout
. To attach the event handler, I utilize bind
.
The callback function receives additional parameters. I have experimented with both callback(parameters)
and `callback.call(this,parameters).
Here is an example of the code:
var element=document.querySelector('h1');
element.onclick=function(e) {
delay(test.bind(element,'from original','also from original',e));
}
function test(a,b,c,d,e) {
alert(this); // element
alert(a); // from original
alert(b); // also from original
alert(c); // event
alert(d); // from delayed
alert(e); // also from delayed
}
function delay(callback) {
window.setTimeout(delayed,100);
function delayed() {
// callback.call(this,'from delayed','also from delayed');
callback('from delayed','also from delayed');
}
}
In my testing, I noticed that the callback receives parameters in the following order:
- Parameters from the original function
- The event itself
- Parameters from the function calling the callback
Additionally, the callback function's this
refers to the initial element, regardless of setting it differently when using .call
.
Although I can work around this issue, I am curious about its formal explanation. I haven't found any documentation addressing an event listener with a callback.
My questions are:
- Where can I find documentation on the parameter ordering?
- Why does
this
remain unchanged despite attempts to modify it?
Thank you