Created
April 30, 2010 07:00
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* 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; | |
}; |
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.
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
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
ortriggerHandler
to literally call the handler with a new$.Event
object.Let me fork this.