addEventListener 使用 apply() [英] addEventListener using apply()
问题描述
我正在尝试使用 apply() 方法调用 addEventListener().代码如下:
<前>函数重写(旧){返回函数(){console.log('添加东西到' + old.name );old.apply(this, arguments);}}addEventListener=rewrite(addEventListener);它不起作用.该代码适用于普通的 JavaScript 方法,例如,
<前>函数 hello_1(){console.log("你好世界 1!");}你好_1=重写(你好_1);需要帮助!
谢谢!
不幸的是,您不能指望 addEventListener
成为真正的 Javascript 函数.(其他几个主机提供的函数也是如此,例如 window.alert
).许多浏览器做正确的事情(tm) 并使它们成为真正的 Javascript 功能,但有些浏览器没有(我在看着你,微软).如果它不是真正的 Javascript 函数,它就不会将 apply
和 call
函数作为属性.
因此,您实际上无法使用主机提供的函数来真正做到这一点,因为如果您想将任意数量的参数从代理传递到目标,则需要 apply
功能.相反,您必须使用特定函数来创建知道所涉及的宿主函数签名的包装器,如下所示:
//返回一个函数,它将事件处理程序连接到给定的//元素.功能代理AEL(元素){返回函数(事件名称,处理程序,阶段){//这是有效的,因为这个匿名函数是一个闭包,//关闭"`element` 参数element.addEventListener(eventName, handler, phase);}}
当您调用它时,传入一个元素,它会返回一个函数,该函数将通过 addEventListener
将事件处理程序连接到该元素.(请注意,IE8 之前的 IE 没有 addEventListener
,但它使用 attachEvent
代替.)
不知道这是否适合您的用例(如果不适合,有关用例的更多详细信息会很方便).
你会像这样使用上面的:
//为 btnGo 上的 addEventListener 函数获取代理var proxy = proxyAEL(document.getElementById('btnGo'));//用它来钩住点击事件代理('点击',去,假);
注意,我们在调用它时没有将元素引用传递给proxy
;它已经内置到函数中,因为函数是一个闭包.如果你不熟悉它们,我的博客文章 闭包并不复杂可能有用.
这是一个完整的例子:
<头><meta http-equiv="Content-type" content="text/html;charset=UTF-8"><title>测试页</title><style type='text/css'>身体 {字体系列:无衬线;}#log p {边距:0;填充:0;}</风格><script type='text/javascript'>window.onload = pageInit;函数 pageInit() {无功代理;//为 btnGo 上的 addEventListener 函数获取代理proxy = proxyAEL(document.getElementById('btnGo'));//用它来钩住点击事件代理('点击',去,假);}//返回一个将事件处理程序连接到给定的函数//元素.功能代理AEL(元素){返回函数(事件名称,处理程序,阶段){//这是有效的,因为这个匿名函数是一个闭包,//关闭"`element` 参数element.addEventListener(eventName, handler, phase);}}函数去(){log('btnGo 被点击了!');}功能日志(味精){var p = document.createElement('p');p.innerHTML = msg;document.getElementById('log').appendChild(p);}头部><body><div><input type='button' id='btnGo' value='Go'><小时><div id='log'></div></div></body>
关于您在下面关于 func.apply()
与 func()
的问题,我想您可能已经理解了,只是我最初的错误答案混淆了问题.但以防万一:apply
调用函数,做两件特别的事情:
- 设置函数调用中的
this
. - 接受参数作为数组(或任何类似数组的东西)提供给函数.
您可能知道,Javascript 中的 this
与其他一些语言(如 C++、Java 或 C#)中的 this
完全不同.Javascript 中的 this
与定义函数的位置无关,它完全取决于函数的调用方式.每次调用函数时都必须将 this
设置为正确的值.(更多关于this
在Javascript这里.) 有两种方法可以做到这一点:
- 通过对象属性调用函数;将
this
设置为调用中的对象.例如,foo.bar()
将this
设置为foo
并调用bar
. - 通过其自身的
apply
或call
属性调用函数;那些将this
设置为他们的第一个参数.例如,bar.apply(foo)
或bar.call(foo)
会将this
设置为foo
并调用bar
.
apply
和 call
之间的唯一区别是它们如何接受传递给目标函数的参数:apply
接受它们作为数组(或类似数组的东西):
bar.apply(foo, [1, 2, 3]);
而 call
接受它们作为单独的参数:
bar.apply(foo, 1, 2, 3);
它们都调用 bar
,将 this
设置为 foo
,并传入参数 1、2 和 3.
I'm trying to invoke addEventListener() using apply() method. The code is like:
function rewrite(old){ return function(){ console.log( 'add something to ' + old.name ); old.apply(this, arguments); } } addEventListener=rewrite(addEventListener);
It doesn't work. The code works for normal JavaScript method, for example,
function hello_1(){ console.log("hello world 1!"); } hello_1=rewrite(hello_1);
Need help!
Thanks!
You can't count on addEventListener
being a real Javascript function, unfortunately. (This is true of several other host-provided functions, like window.alert
). Many browsers do the Right Thing(tm) and make them true Javascript functions, but some browsers don't (I'm looking at you, Microsoft). And if it's not a real Javascript function, it won't have the apply
and call
functions on it as properties.
Consequently, you can't really do this generically with host-provided functions, because you need the apply
feature if you want to pass an arbitrary number of arguments from your proxy to your target. Instead, you have to use specific functions for creating the wrappers that know the signature of the host function involved, like this:
// Returns a function that will hook up an event handler to the given
// element.
function proxyAEL(element) {
return function(eventName, handler, phase) {
// This works because this anonymous function is a closure,
// "closing over" the `element` argument
element.addEventListener(eventName, handler, phase);
}
}
When you call that, passing in an element, it returns a function that will hook up event handlers to that element via addEventListener
. (Note that IE prior to IE8 doesn't have addEventListener
, though; it uses attachEvent
instead.)
Don't know if that suits your use case or not (if not, more detail on the use case would be handy).
You'd use the above like this:
// Get a proxy for the addEventListener function on btnGo
var proxy = proxyAEL(document.getElementById('btnGo'));
// Use it to hook the click event
proxy('click', go, false);
Note that we didn't pass the element reference into proxy
when we called it; it's already built into the function, because the function is a closure. If you're not familiar with them, my blog post Closures are not complicated may be useful.
Here's a complete example:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
#log p {
margin: 0;
padding: 0;
}
</style>
<script type='text/javascript'>
window.onload = pageInit;
function pageInit() {
var proxy;
// Get a proxy for the addEventListener function on btnGo
proxy = proxyAEL(document.getElementById('btnGo'));
// Use it to hook the click event
proxy('click', go, false);
}
// Returns a function that will hook up an event handler to the given
// element.
function proxyAEL(element) {
return function(eventName, handler, phase) {
// This works because this anonymous function is a closure,
// "closing over" the `element` argument
element.addEventListener(eventName, handler, phase);
}
}
function go() {
log('btnGo was clicked!');
}
function log(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.getElementById('log').appendChild(p);
}
</script>
</head>
<body><div>
<input type='button' id='btnGo' value='Go'>
<hr>
<div id='log'></div>
</div></body>
</html>
Regarding your question below about func.apply()
vs. func()
, I think you probably already understand it, it's just that my original wrong answer confused matters. But just in case: apply
calls function, doing two special things:
- Sets what
this
will be within the function call. - Accepts the arguments to give to the function as an array (or any array-like thing).
As you probably know, this
in Javascript is quite different from this
in some other languages like C++, Java, or C#. this
in Javascript has nothing to do with where a function is defined, it's set entirely by how the function is called. You have to set this
to the correct value each and every time you call a function. (More about this
in Javascript here.) There are two ways to do that:
- By calling the function via an object property; that sets
this
to the object within the call. e.g.,foo.bar()
setsthis
tofoo
and callsbar
. - By calling the function via its own
apply
orcall
properties; those setthis
to their first argument. E.g.,bar.apply(foo)
orbar.call(foo)
will setthis
tofoo
and callbar
.
The only difference between apply
and call
is how they accept the arguments to pass to the target function: apply
accepts them as an array (or an array-like thing):
bar.apply(foo, [1, 2, 3]);
whereas call
accepts them as individual arguments:
bar.apply(foo, 1, 2, 3);
Those both call bar
, seting this
to foo
, and passing in the arguments 1, 2, and 3.
这篇关于addEventListener 使用 apply()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!