0

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);
});
clinton3141
  • 4,751
  • 3
  • 33
  • 46
Oliver
  • 1,576
  • 1
  • 17
  • 31

1 Answers1

2

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))
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • How would I pass parameters other than the special parameter? – Oliver Dec 22 '16 at 08:10
  • Also, the `this` scope is then impossible to use, meaning I can't reference other things in `handler` – Oliver Dec 22 '16 at 08:11
  • If you're going to pass other parameters, just use the code you wrote in the question. – Barmar Dec 22 '16 at 08:12
  • `bind1Arg` passes on `this` in the `.apply()` call. – Barmar Dec 22 '16 at 08:13
  • See the duplicate question for how to bind an arbitrary number of arguments, not just the first argument. – Barmar Dec 22 '16 at 08:14
  • Unless bindArg1 is part of `handler` it passes the wrong scope – Oliver Dec 22 '16 at 08:16
  • When you do `whenEventOccurs('event-name', handler.eventName)`, the scope isn't `handler`, it's whatever `whenEventOccurs` sets as the scope when it calls the callback. When you use `bindArg1`, the same thing happens. – Barmar Dec 22 '16 at 08:18
  • You can write `bindArg1(handler.eventName.bind(handler), specialParam)` – Barmar Dec 22 '16 at 08:21