Skip to content

Instantly share code, notes, and snippets.

@cowboy
Forked from westonruter/jquery.bindAndCall.js
Created April 30, 2010 12:49
Show Gist options
  • Save cowboy/385142 to your computer and use it in GitHub Desktop.
Save cowboy/385142 to your computer and use it in GitHub Desktop.
Bind an event handler and fire it immediately
/*!
* bindAndTrigger - v0.1 - 04/30/2010
* http://benalman.com/
*
* http://jsfiddle.net/cowboy/fJnA2/
*/
(function($,undefined){
$.fn.bindAndTrigger = function( all, type, data, callback ) {
if ( typeof all !== 'boolean' ) {
callback = data;
data = type;
type = all;
all = undefined;
}
var first = type.split(' ')[0],
fn = callback || data;
return this
.bind( type, data, callback )
.each(function(){
var event = $.Event( first );
fn.call( event.target = this, event );
return !!all;
});
};
})(jQuery);
@cowboy
Copy link
Author

cowboy commented Apr 30, 2010

I used to have a lot of fancy arguments stuff in jQuery Object Utils (predecessor to jQuery getObject) but it ended up being a bit gross. In this particular example, it actually simplified things greatly (imo) to use explicit vars.

One or two if statements to shift args around might not feel beautiful, but it minifies really small and executes super-fast.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment