【发布时间】:2013-05-25 01:44:58
【问题描述】:
问题
如果没有原始事件参数,是否可以知道该函数是由用户事件还是异步事件(如回调)触发的?
背景
我正在尝试在不知道谁是原始事件触发器的更深层次的函数调用中确定事件源。
为了调用弹出或重定向登录系统,我必须知道这一点。但是这个函数是从很多地方调用的,所以我无法在所有调用者中传递事件参数。
重要提示:我无法将参数传递给最终函数。不允许使用b('timer')。
例如:
<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);
在该示例中,我尝试获取 source == 'timer' 或 'onclick',或任何其他信息以确定事件来源。
更新
基于 basilikun 方法,我实现了这个解决方案:
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');
}
这是finddle
还有其他方法吗?
【问题讨论】:
-
为什么不能将参数传递给
b? -
你定义
a是为了什么? -
所以
b("timer")是不可能的,但至少可以将某些东西传递给事件调用的第一个函数(到a)吗? -
@Asad:抱歉,我更新了我的示例,现在调用了 a()。
-
@user1737909:我无法将参数传递给 b,因为在我的真实代码中,b 是从多个地方的文档中调用的,其中许多地方我无法管理。
标签: javascript events javascript-events