Skip to content

Instantly share code, notes, and snippets.

@micmro
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micmro/8e1c2fd3775d9e23889b to your computer and use it in GitHub Desktop.
Save micmro/8e1c2fd3775d9e23889b to your computer and use it in GitHub Desktop.
Non blocking event listener for jQuery
/*
* usage: exactly like like jQuery's `on`
* $("#xyz").on("click", function(){ ... }); => $("#xyz").asyncOn("click", function(){ ... });
* $("#xyz").one("click", function(){ ... }); => $("#xyz").asyncOne("click", function(){ ... });
*/
$.fn.extend({
asyncOn : function(types, selector, data, fn, one){
/*based on https://github.com/jquery/jquery/blob/361a0d5150a1c57b1857611cde1b05bd0ef21a50/src/event.js*/
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
//This is the only change - wrap fn in a setTimeout
jQuery.event.add( this, types, function(){
var args = $.makeArray(arguments);
setTimeout(function(){
fn.apply(this, args);
});
}, data, selector );
});
},
asyncOne : function(types, selector, data, fn){
return this.asyncOn( types, selector, data, fn, 1 );
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment