Skip to content

Instantly share code, notes, and snippets.

@westonruter
Created April 30, 2010 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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;
};
@cowboy
Copy link

cowboy commented Apr 30, 2010

Keep in mind that this will also execute all other event handlers bound on that element for that event and bubble up the DOM tree, triggering any other handlers bound to ancestor elements.

You could use triggerHandler to just execute the bound callbacks without bubbling an event up the DOM tree, but that will still execute other bound event handlers on the current element.

A better solution might be to, instead of calling trigger or triggerHandler to literally call the handler with a new $.Event object.

Let me fork this.

@westonruter
Copy link
Author

You mean doing $foo.change(handler).change() will execute all other bound event handlers and bubble, not my bindAndFire method, right?

Excellent point about triggerHandler! I definitely should have been using it instead of my anti-pattern with ~trigger.

I've been looking at your fork. I'm going to fork your fork.

@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