0

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);

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I guess I have to go with wrapping function, because I need cross browser compatibility. Let me try !
@dvLden I would also choose that one. But be aware bind can be polyfied for old browsers.
Oh thanks for polyfill :) ! Well I tried first method, I will try polyfill too but I guess wrapper will just do fine!
1

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.

2 Comments

Is there any polyfill for cross browser support (IE 6 and above) ?
If you don't store any reference to the function returned by myHandler.bind(this, myVar), you won't be able to remove the event listener.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.