force javascript EventListener to execute once?

44,300
var clickFunction = function (event) {
    //do some stuff here
    window.removeEventListener('click',clickFunction, false );

};
window.addEventListener("click", clickFunction, false);

This will let you fire the clickFunction once, as the magic of closure let the removeEventListener find the clickFunction.

No need to use a library just to get something simple done.

Share:
44,300
Skizit
Author by

Skizit

Hi!

Updated on July 09, 2022

Comments

  • Skizit
    Skizit almost 2 years

    I'm wondering is it possible for force a javascript event listener to, without the condition being true force it to execute once then continue listening for it's condition to be met to execute further?

  • KOGI
    KOGI over 13 years
    if you need the function to be in a particular context, you can use jQuery's proxy( ) method api.jquery.com/jQuery.proxy
  • Dmytro
    Dmytro over 7 years
    This quickly becomes a problem if you need to use this pattern more than twice in one code. This is very common in css animation contexts where you have an animation "hook transitionend, set change, make transitionend remove itself", and often you have to chain it. A pattern similar to hastebin.com/ikixonajuk.coffee is far more maintainable. In NodeJS it is just called "once".
  • Jlam
    Jlam over 7 years
    1. in 2011 when the answer was originally posted, once wasn't available. 2. that's a client side implementation question in the original question so nodejs isn't helpful 3. your coffee script is essentially the same idea with slight modification.
  • Dmytro
    Dmytro over 7 years
    is once available now in browser through or do we still have to invent it/use bloated third party libraries for it?
  • Jlam
    Jlam over 7 years
    implementing your own once function is only a couple lines. Something like this would work. window.once = function(aFun) { var clickFunction = function (event) { aFun(); window.removeEventListener('click',clickFunction, false ); }; window.addEventListener("click", clickFunction, false); } window.once(function() { .... })
  • Dmytro
    Dmytro over 7 years
    I am aware, I posted this earlier for reference which works for any event hastebin.com/ikixonajuk.coffee. The difference between it "just being there" and having to invent it is fairly large when it comes to how clean code is. It's just at this point I find most events I deal with are "run once". Even 'load' may as well be removed after it's called, so it's surprising there isn't a builtin for it. A native implementation of it would probably be more efficient as well.