Query
Can we determine the origin of a function being triggered by either a user event or an async event, without having access to the original event parameter?
Situation
I am faced with the challenge of identifying the event source within a nested function call that is unaware of who initially triggered the event.
This information is crucial for executing actions like displaying a popup or initiating a login redirection. However, since this function is invoked from various places, passing the event parameter in all callers is not feasible.
Note: I cannot pass parameters to the final function. The use of b('timer')
is prohibited.
Example:
<a onclick="b()" >call</a>
<script>
function a(){
b();
}
function b(){
final();
}
function final(){
//Is there something like this caller.event.source ?
console.log(this.caller.event.source)
}
setTimeout(a,1000);
In this scenario, I aim to retrieve source == 'timer'
or 'onclick'
, or any other relevant information to determine the event's origin.
Update
Following basilikun's method, I have implemented the following solution:
function final(){
var callerFunction = arguments.callee.caller,
evtArg = callerFunction.arguments[0];
while(callerFunction.caller){
callerFunction = callerFunction.caller;
if (callerFunction.arguments[0]) {
evtArg = callerFunction.arguments[0];
}
}
console.log(evtArg&&evtArg.type?'event fired by user':'event async');
}
You can view the code in action on this JSFiddle link
Any alternative approaches suggested?