dvlden
dvlden

Reputation: 2462

JS Event Listener with a function that has one parameter

Not sure how to set proper title for this question, so I guess that's why I can't find anything related to it.

Suggestion for title would be nice if this isn't a duplicate already.

I wonder how do I actually add/remove event listener with a function where I must pass one parameter.

Simple example as it should be is below:

window.addEventListener('resize', anFunction, false);
window.removeEventListener('resize', anFunction, false);

But how do I set the same function that must contain parameter within ? Example below that is invalid of course, as I don't know how to do it.

window.addEventListener('resize', anFunction(parameter), false);
window.removeEventListener('resize', anFunction(parameter), false);

Upvotes: 0

Views: 42

Answers (2)

Ahrengot
Ahrengot

Reputation: 1589

There is also the relatively new (IE9+) function.prototype.bind method

It works like this:

var myVar = "123";

var myHandler = function(myVar) {
    console.log("Resize handler with arg: ", myVar);
    // => Resize handler with arg: 123
};

window.addEventListener("resize", myHandler.bind(this, myVar));

It's meant to be used for controlling the context (value of this) of callbacks, but it's also works nicely for things like what you described.

Upvotes: 1

Oriol
Oriol

Reputation: 288100

For example, you can use one of these:

  • A wrapping function:

    function resizeListener() {
        anFunction(parameter);
    }
    
  • Function.prototype.bind:

    var resizeListener = anFunction.bind(void 0, parameter);
    
  • An arrow function (EcmaScript6):

    var resizeListener = e => anFunction(parameter);
    

And then:

window.addEventListener('resize', resizeListener, false);
window.removeEventListener('resize', resizeListener, false);

Upvotes: 1

Related Questions