Skip to content

Instantly share code, notes, and snippets.

@westonruter
Created April 30, 2010 07:00
Show Gist options
  • Save westonruter/384866 to your computer and use it in GitHub Desktop.
Save westonruter/384866 to your computer and use it in GitHub Desktop.
jQuery.fn.bindAndCall(type, callback): Not only bind a handler to an event, but also call it immediately once.
/*!
* Not only bind a handler to an event, but also call it immediately once.
* @param {string} event One or more event types separated by spaces. Only first listed will be immediately called.
* @param {function(Object)} callback The event handler
* @returns {jQuery}
*/
jQuery.fn.bindAndCall = function(type, callback){
this.bind(type, callback);
var types = type.split(/\s+/); //because only one type makes sense to call
this.each(function(){
var event = $.Event(types[0]);
event.target = this;
callback.call(this, event);
return !event.isImmediatePropagationStopped();
});
return this;
};
@westonruter
Copy link
Author

I also added support for event.stopImmediatePropagation()

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