nikoss
nikoss

Reputation: 3688

Once function keeps executing

I wrote a once event listener function but it keeps executing as usual event listener not once here is the working code and below the function i wrote

window.once=function(event,cb){
  function ccb(e){
    event=e||window.event;
    if(event){
      cb(event);
      this.removeEventListener(event,ccb);
    }
  }
  this.addEventListener(event,ccb);
}

window.Element.prototype.once=function(event,cb){
  function ccb(e){
    event=e||window.event;
    if(event){
      cb(event);
      this.removeEventListener(event,ccb);
    }
  }
  this.addEventListener(event,ccb);
}

Upvotes: 0

Views: 52

Answers (1)

MartyB
MartyB

Reputation: 135

you are getting this problem because you are trying to remove the MouseEvent event, instead of the MouseEvent. To clarify this, try this:

....
function ccb(e){
    event=e||window.event;
    if(event){
       console.log(event);
    }
}
....

logs the event MouseEvent itself, while

window.once=function(event,cb){
    function ccb(e){
       ....
    }
    console.log(event)
    this.addEventListener(event,ccb);
}

logs the string Click

The solution for this is to access the key type from your mouseevent, e.g.

window.once=function(event,cb){
    function ccb(e){
        event=e||window.event;
        if(event){
            cb(event);
            this.removeEventListener(event.type,ccb);
       }
    }
    this.addEventListener(event,ccb);
}

Upvotes: 1

Related Questions