使用 apply() 添加事件监听器

发布于 2024-09-02 18:45:17 字数 421 浏览 4 评论 0原文

我正在尝试使用 apply() 方法调用 addEventListener() 。代码是这样的:

function rewrite(old){
    return function(){
        console.log( 'add something to ' + old.name );
        old.apply(this, arguments);
    }
} 
addEventListener=rewrite(addEventListener);

它不起作用。该代码适用于普通 JavaScript 方法,例如,

function hello_1(){
    console.log("hello world 1!");
}
hello_1=rewrite(hello_1);

需要帮助!

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无言温柔 2024-09-09 18:45:17

不幸的是,您不能指望 addEventListener 是一个真正的 Javascript 函数。 (对于其他几个主机提供的函数也是如此,例如window.alert)。许多浏览器都会做正确的事情(tm)并使其成为真正的Javascript函数,但有些浏览器却没有(我正在看着你,微软)。如果它不是真正的 Javascript 函数,则它不会将 applycall 函数作为属性。

因此,您实际上无法使用主机提供的函数来执行此操作,因为如果您想将任意数量的参数从代理传递到目标,则需要 apply 功能。相反,您必须使用特定的函数来创建知道所涉及的主机函数的签名的包装器,如下所示:

// 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);
    }
}

当您调用该函数时,传入一个元素,它会返回一个函数,该函数将通过 < 将事件处理程序连接到该元素代码>addEventListener。 (请注意,IE8 之前的 IE 没有 addEventListener;它使用 attachEvent 代替。)

不知道这是否适合您的用例(如果不适合) ,有关用例的更多详细信息会很方便)。

您可以像这样使用上面的内容:

// 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);

请注意,当我们调用它时,我们没有将元素引用传递给 proxy ;它已经内置到函数中,因为该函数是一个闭包。如果您不熟悉它们,请参阅我的博客文章 闭包并不复杂可能会有用。

这是一个完整的例子:

<!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>

关于下面关于 func.apply()func() 的问题,我想你可能已经明白了,只是我原来的错误答案混乱的事情。但以防万一:apply 调用函数,执行两项特殊操作:

  1. 设置 this 在函数调用中的内容。
  2. 接受参数作为数组(或任何类似数组的东西)提供给函数。

您可能知道,Javascript 中的 this 与 C++、Java 或 C# 等其他语言中的 this 有很大不同。 Javascript 中的 this 与函数的定义位置无关,它完全由函数的调用方式设置。每次调用函数时,都必须将 this 设置为正确的值。 (有关 Javascript 中 this 的更多信息此处< /a>.) 有两种方法可以做到这一点:

  • 通过对象属性调用函数;将 this 设置为调用中的对象。例如,foo.bar()this 设置为 foo 并调用 bar
  • 通过函数自身的 applycall 属性调用该函数;那些将 this 设置为其第一个参数。例如, bar.apply(foo)bar.call(foo) 会将 this 设置为 foo 并调用

applycall 之间的唯一区别是它们如何接受传递给目标函数的参数:apply 将它们作为数组(或类似数组的东西):

bar.apply(foo, [1, 2, 3]);

call 接受它们作为单独的参数:

bar.apply(foo, 1, 2, 3);

它们都调用 bar,将 this 设置为 foo,并传入参数 1、2 和 3。

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:

  1. Sets what this will be within the function call.
  2. 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() sets this to foo and calls bar.
  • By calling the function via its own apply or call properties; those set this to their first argument. E.g., bar.apply(foo) or bar.call(foo) will set this to foo and call bar.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文