Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: bind arguments, but keep original ones?

Tags:

javascript

I would like to inject some values to event listener's callback in JavaScript, but keeping the original event object. Is that possible?

Example (#1):

function callback(event, arg) {
    console.log(event);
    console.log(arg);
}

var something = 2;

element.addEventListener(
    "click",
    callback.bind(element, ???, something)
);

How can I keep original event object while binding another arguments?

I know I can do this (#2):

element.addEventListener(
    "click",
    function (event) {
        callback(event, something);
    }
);

Or even this (#3):

element.addEventListener(
    "click",
    function (event) {
        callback(event, this);
    }.bind(something)
);

But #2 makes the code uglier, because I need to use variable something in asynchronous call, while it could have been changed at the moment of the click.

The #3 steals this and I might need that.

Am I missing something and/or is my understanding of binding correct?

like image 336
Robo Robok Avatar asked Apr 20 '26 20:04

Robo Robok


1 Answers

You can "curry" the arguments you want by shifting the order of your arguments around:

function callback(arg, event) {
    console.log(event);
    console.log(arg);
}

var something = 2;
element.addEventListener("click", callback.bind(null, something));

This way you pass the "bound" or partially applied as a callback and still receive an Event object. For more information, see the "Partial Functions" section of the the MDN Function.prototype.bind docs.

like image 63
Nick Tomlin Avatar answered Apr 23 '26 11:04

Nick Tomlin