Skip to content

Instantly share code, notes, and snippets.

@EtienneLem
Created September 3, 2013 19:03
Show Gist options
  • Save EtienneLem/6428157 to your computer and use it in GitHub Desktop.
Save EtienneLem/6428157 to your computer and use it in GitHub Desktop.
$('a').one('click', callback) is executed at most once *per element*. $('a').one_for_all('click', callback) is executed at most once… *for all elements*.
// Works with Zepto/jQuery
$.fn.one_for_all = function(type, callback) {
var $all = $(this)
$all.on(type, function(e) {
$all.off(type)
callback(e)
})
}
$links = $('a')
// .one()
$links.one('click', function(e) { console.log('clicky') })
$links.eq(0).trigger('click') // => clicky
$links.eq(0).trigger('click')
$links.eq(1).trigger('click') // => clicky
$links.eq(1).trigger('click')
$links.eq(2).trigger('click') // => clicky
$links.eq(2).trigger('click')
// .one_for_all()
$links.one_for_all('click', function(e) { console.log('clicky') })
$links.eq(0).trigger('click') // => clicky
$links.eq(0).trigger('click')
$links.eq(1).trigger('click')
$links.eq(1).trigger('click')
$links.eq(2).trigger('click')
$links.eq(2).trigger('click')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment