JavaScript pre set function parameter

44 views Asked by At

I have a series of events I'm listening to (not DOM ones), and an object containing event handler functions.

Typically I'd do something like

whenEventOccurs('event-name', handler.eventName)

Except that I have to pass a parameter to the handler that changes for every event listener.

I am looking for something like Function.prototype.bind() that doesn't set this but sets the first parameter, if possible.

If there is no clean solution, I can always do the following, but I'd like to avoid it if possible:

whenEventOccurs('event-name', function(foo, bar, baz){
    handler.eventName(specialParam, foo, bar, baz);
});
1

There are 1 answers

8
Barmar On

You can encapsulate it in a function that works similarly to bind()

function bindArg1(func, arg1) {
    return function() {
        var args = [].slice.call(arguments);
        args.unshift(arg1);
        return func.apply(this, args);
    }
}

whenEventOccurs('event-name', bindArg1(handler.eventName, specialParam))