views:

44

answers:

1

I'm working with animation in JavaScript, and I have a bunch of functions you can call to add things to the animation queue. Basically, all of these functions look like this:

function foo(arg1, arg2) {
    _eventQueue.push(function() {
        // actual logic
    }
 }

I'm wondering now if it would be possible to cut down on this boilerplate a little bit, though, so I don't need that extra "_eventQueue" line in each function body dozens of times. Would it be possible, for example, to make a helper function which takes an arbitrary function as an argument and returns a new function which is augmented to be automatically added to the event queue? The only problem is that I need to find a way to maintain access to the function's original arguments in this process, which is... complicated.

+3  A: 

You're looking for the arguments identifier, which gives an array-like object containing the arguments that were passed to the current function.

For example:

function createEnqueuer(func) {
    return function() {
        var outerArgs = arguments;

        _eventQueue.push(function() {
            return func.apply(window, outerArgs);
        });
    };
}
SLaks
Dang, beat me to it. However, I'm not sure I agree with calling apply with `this` set to `window`. Although this code currently follows existing JavaScript convention (by matching what `this` is set to when you call a function not as a method), it provides little benefit, and it is subject to change in EMCAScript 5. If I'm not mistaken, `this` will be set to `undefined` instead. Disclaimer: I am by no means an expert on this subject; I just so happened to watch this yesterday: http://www.yuiblog.com/blog/2010/02/24/video-crockonjs-3/ .
Joey Adams
Can you see any potential issues with calling `func.apply(this, outerArgs)`?
Sidnicious
Awesome... how does this work? I would have assumed that the arguments array would hold the arguments to the createEnqueuer function, not to the func function.
Derek Thurn
@thurn: The `arguments` keyword gives the arguments of whatever function it's referenced in. (even if the function doesn't declare any arguments)
SLaks
@Sidnicious: It depends how he wants the function to be invoked, and how `_eventQueue` calls its parameter.
SLaks
@SLaks: Oh! I get it. 'arguments' refers to the arguments of the anonymous function you return, but it's *invoked* with all of the arguments of the original function. I was confused because I forgot you didn't have to declare all of a function's arguments in the signature... you can just pass them in and access them via the arguments array. That is some cool stuff!
Derek Thurn