Derek Thurn
Derek Thurn

Reputation: 15375

Reduce boilerplate of adding functions to a function queue

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.

Upvotes: 4

Views: 146

Answers (1)

SLaks
SLaks

Reputation: 887489

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

Upvotes: 3

Related Questions