我有一个预先绑定(bind)到特定变量的事件处理程序(通过 $.proxy
)。因此,当处理程序被触发时,this
不是正常值,而是我的预绑定(bind)值。
我想使用处理程序的 event
参数恢复 this
,但是 this
似乎没有直接映射到 event.currentTarget
、event.target
或任何其他事件属性。
因此,我已经尝试挖掘 jQuery 源代码,但事件回调的内容非常复杂,我无法弄清楚 this
的确切设置。有谁知道如何仅使用事件参数模拟 jQuery 事件处理程序 this
?
* * 编辑 * *
为了澄清,这里有一个例子:
var boundThis = {foo: 'bar'}
var handler = $.proxy(function(event) {
// Because of the $.proxy, this === boundThis
// (NOT the normal "this" that jQuery would set)
// In theory event has everything I need to re-create this,
// but I'm having trouble figuring out exactly how
// Here's a naive/non-functional example of what I'm trying to do
jQueryThis = event.target; // If only this worked ...
}, boundThis);
$(someElement).click(handler);
最佳答案
event.currentTarget
通常是 this
与 jQuery 事件的值。如所述in the docs :
Description: The current DOM element within the event bubbling phase.
演示:http://jsfiddle.net/rhgEB/ .
虽然 event.target
保持为 #baz
,但 event.currentTarget
引用正在处理的当前元素;与没有 proxy
的 this
相同。
* * machineghost 编辑 * *
只是为了节省 future 的读者一些时间,基于事件对象(“e
”)生成 this
等价物的“神奇公式”是:
var fakeThis = e.delegateTarget === e.currentTarget ? e.currentTarget : e.target;
关于javascript - 如何在事件处理程序中重新创建 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11303114/