开发者

addEventListener using apply()

开发者 https://www.devze.com 2022-12-31 02:35 出处:网络
I\'m trying to invoke addEventListener() using apply() method. The code is like: function rewrite(old){

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, argu开发者_如何学运维ments);
    }
} 
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:

  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.

0

精彩评论

暂无评论...
验证码 换一张
取 消