jQuery.one listening multiple events

jQuery's $.fn.one is supposed to be turned off after an event had been fired, and the listener had run the script.

However, if it's listening to multiple events, it won't turn off for all listened events after one of them firing.

Using this event listener:

var transitionend = "webkitTransitionEnd msTransitionEnd transitionend";

$( "foo" ).one( transitionend , function(){ 

   foo.bar(); 

} );

The foo.bar() method will be executed 2 times in chrome, since webkitTransitionEnd transitionend both fire.

I am trying to achieve an elegant solution where firing one of the listened methods turns off all others in the listener.

Upvotes: 1

Views: 218

Answers (1)

Carl
Carl

Reputation: 1816

I think your best bet may be to just manually remove the binding once the event has fired?

Somthing like:

var transitionend = "webkitTransitionEnd msTransitionEnd transitionend";
$( "foo" ).on( transitionend , function(){ 
   foo.bar(); 
   $(this).off(transitionend); 
} );

Edit: If you're after a more elegant looking solution (assuming you'd need to be doing this kinda thing a lot) it looks like someone has wrapped the above in to a reusable function on another Stack Overflow answer: https://stackoverflow.com/a/24589200/820822

Also: jQuery's One - Fire once with multiple event types appears to be the same question, so may have some other useful answers.

Upvotes: 4

Related Questions