Skip to content Skip to sidebar Skip to footer

Add Additional Parameters To Event Function

I have an event, and I want to add additional parameters to the named function. I tried following two things: myDiv.addEventListener('click', evt.call(this, event, 'hello')); And

Solution 1:

You can use an anonymous wrapper:

myDiv.addEventListener('click', function(event) {
    return evt.call(this, event, 'hello');
});

Alternately, you can give yourself a utility function (I tend to call it curry; purist may argue with that name). Here's an unoptimized off-the-cuff:

Object.defineProperty(Function.prototype, "curry", {
    value: function() {
        var f = this;
        var boundArgs = Array.prototype.slice.call(arguments);
        returnfunction() {
            return f.apply(this, boundArgs.concat(Array.prototype.slice.call(arguments)));
        };
    }
});

Then:

myDiv.addEventListener('click', evt.curry('hello'));

But you have to change the order of arguments in evt for that:

function evt(param1, event) {
  console.log(event + ' and ' + param1)
}

...since my version of curry passes it the curried arguments first, then the arguments that the curried version was called with. Although I suppose it's easy enough to swap them around if you prefer.

Here's that curry function in ES2015+:

Object.defineProperty(Function.prototype, "curry", {
    value(...boundArgs) {
        var f = this;
        returnfunction(...callArgs) {
            return f.call(this, ...boundArgs, ...callArgs);
        };
    }
});

Solution 2:

Just use an anonymous function for your event handler, that calls your evt function and passes in the event object and a parameter:

myDiv.addEventListener('click', function ( e ) {
  evt( e, 'hello' );
} );

Post a Comment for "Add Additional Parameters To Event Function"