Skip to content

Instantly share code, notes, and snippets.

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 westonruter/385402 to your computer and use it in GitHub Desktop.
Save westonruter/385402 to your computer and use it in GitHub Desktop.
/*!
* bindAndTrigger - v0.2 - 04/30/2010
* http://benalman.com/ (original v0.1 at http://gist.github.com/384866 )
* http://weston.ruter.net/ (playing around with improving variable args)
*
* http://jsfiddle.net/cowboy/fJnA2/
*/
(function($,undefined){
$.fn.bindAndTrigger = function( /*...*/ ) {
// Default values for arguments
var isTriggerAll = true,
type,
data = null,
callback;
// Variable function arguments via destructuring assignment (JS 1.7 goodness)
switch(arguments.length){
// type, callback
case 2:
[type, callback] = arguments;
break;
// isTriggerAll, type, callback
// type, data, callback
case 3:
if(typeof arguments[0] == 'boolean'){
[isTriggerAll, type, callback] = arguments;
}
else {
[type, data, callback] = arguments;
}
break;
// isTriggerAll, type, data, callback
case 4:
[isTriggerAll, type, data, callback] = arguments;
break;
}
// Check argument types
function assertType( arg, argName, dataType ){
if(typeof arg != dataType){
throw TypeError("Argument `" + argName + "` is not a " + dataType);
}
}
assertType( isTriggerAll, 'isTriggerAll', 'boolean' );
assertType( type, 'isTriggerAll', 'string' );
assertType( callback, 'callback', 'function' );
// Bind the callback to the event
this.bind( type, data, callback );
// Trigger the handler with the first event type (one one makes sense)
var firstType = type.split(' ')[0];
this.each(function(){
var event = $.Event( firstType );
event.target = this;
callback.call( this, event );
return isTriggerAll;
});
return this;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment