views:

130

answers:

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!

+3  A: 

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.

T.J. Crowder
I might not konw the signature of addEvetnListener because it might happen in runtime. Is there any workaround?
Paul
@Paul: `addEventListener` has a specific, defined signature. For real *Javascript* functions, in the general case, you can do what you did. It's just these pesky host-provided functions that may not be "real" that you have to work around, and those will have defined signatures.
T.J. Crowder
@Crowder, Sorry, I either misunderstood or misspoke... What I tried to say is that, given your example code, how do I know the element? (I'm using Firefox.) also, what's the different between func.apply() and func() (i.e., what's the difference btw your code and my code)? Thanks!
Paul
@Paul: I don't know what I was thinking, the above will not work. I was thinking in terms of `addEventListener` accepting the element as the first argument, but of course it doesn't do that, it's called as a method of the element. Off-day, I'm afraid. I'll go update (and answer the question about `apply`).
T.J. Crowder
@T.J., Thanks a lot for the details. addEventListener and a few other host-provided functions are not "real" functions, is it because they are native JavaScript functions? maybe the question can be asked in this way: do all native JavaScript functions have no apply() or just certain native functions don't have?
Paul
@Paul: It's exactly the other way around: All *native* Javascript objects will have the `apply` and `call` features. All of this DOM stuff is from the environment (the browser), not Javascript. Some environments make sure the functions you see at the Javascript layer are real Javascript functions, but unfortunatley many (including IE) don't. The functions can be called from Javascript, but they're not Javascript functions. They're functions provided by the browser's DOM layer.
T.J. Crowder
@T.J., would you like make your last comment as an answer? (I'd like to recommend it as a great answer.) btw, does firefox treat these DOM stuff as real functions? Thanks again!
Paul
@Paul: :-) All of these comments are on an answer of mine, so we'll have to call that good. (You can, however, accept this answer if it's answered your question.) On the which browser does what, your only option is to test -- and test carefully. By way of example, here's a test for `addEventListener` and a couple of other ones: http://pastie.org/981334 Note that I don't assume just because `apply` is present, that it actually works properly; I test that, too (by checking that the hooked element is the correct one). Firefox, Chrome, Opera, and Safari all pass; IE fails.
T.J. Crowder