Skip to content

Instantly share code, notes, and snippets.

@desandro
Created November 15, 2012 03:04
Show Gist options
  • Save desandro/4076383 to your computer and use it in GitHub Desktop.
Save desandro/4076383 to your computer and use it in GitHub Desktop.
add/remove event with handleEvent helper
// modified John Resig's http://ejohn.org/projects/flexible-javascript-events/
var div = document.createElement('div');
var addEvent, removeEvent;
if ( div.addEventListener ) {
addEvent = function( elem, type, fn ) {
elem.addEventListener( type, fn, false );
};
} else if ( div.attachEvent ) {
// <= IE8
addEvent = function( elem, type, fn ) {
var onFn = fn;
// handleEvent fill
if ( fn.handleEvent ) {
onFn = function( event ) {
fn.handleEvent.call( fn, event );
};
}
// hash original function
elem[ 'e' + type + fn ] = onFn;
// hash this function so we can remove it
elem[ type + fn ] = function() {
elem[ 'e' + type + fn ]( window.event );
};
elem.attachEvent( "on" + type, elem[ type + fn ] );
};
}
if ( div.removeEventListener ) {
removeEvent = function( elem, type, fn ) {
elem.removeEventListener( type, fn, false );
};
} else if ( div.detachEvent ) {
// <= IE8
removeEvent = function( elem, type, fn ) {
elem.detachEvent( "on" + type, elem[ type + fn ] );
// delete references
delete elem[ type + fn ];
delete elem[ 'e' + type + fn ];
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment