Skip to content

Instantly share code, notes, and snippets.

@livingston
Created September 30, 2011 12:20
Show Gist options
  • Save livingston/1253593 to your computer and use it in GitHub Desktop.
Save livingston/1253593 to your computer and use it in GitHub Desktop.
Element event monitor, similar to Web Inspector's `monitorEvents`
(function (global) {
if ( !global.Event && !('keys' in Object) && !('bind' in Function) ) { return }
var eventProto = Event.prototype,
EVENTS = {
'mouse': [ 'click', 'dblclick', 'contextmenu', 'mousedown', 'mouseup', 'mouseover', 'mousemove', 'mouseout', 'drag', 'dragend', 'dragenter', 'dragleave', 'dragover', 'drop'],
'key': [ 'keydown', 'keypress', 'keyup', 'input'],
'res': [ 'load', 'unload', 'beforeunload', 'abort', 'error', 'resize', 'scroll', 'readystatechange' ],
'form': [ 'select', 'change', 'submit', 'reset', 'focus', 'blur' ],
'ui': [ 'DOMFocusIn', 'DOMFocusOut', 'DOMActivate', 'DOMCharacterDataModified', 'DOMNodeInserted', 'DOMNodeRemoved', 'DOMSubtreeModified' ],
'other': [ 'copy', 'cut', 'paste' ]
},
ALL_EVENTS = [],
PHASES = [ '', 'CAPTURING_PHASE', 'AT_TARGET', 'BUBBLING_PHASE' ],
logEvent = function ( evt ) {
console.log(evt.type, evt, PHASES[evt.eventPhase]);
},
bindEvents = function (eventName) {
unbindEvents(eventName);
this.addEventListener( eventName, logEvent, false);
},
unbindEvents = function (eventName) {
this.removeEventListener( eventName, logEvent, false);
};
Object.keys(EVENTS).forEach(function ( curr ) { ALL_EVENTS = ALL_EVENTS.concat(EVENTS[curr]); });
global.EventMonitor = {
start: function ( elm, eventType ) {
var binder = bindEvents.bind(elm);
if(!eventType) {
ALL_EVENTS.forEach( binder );
} else if(eventType in EVENTS) {
EVENTS[eventType].forEach( binder );
} else {
binder(eventType);
}
},
stop: function ( elm, eventType ) {
var unbinder = unbindEvents.bind(elm);
if(!eventType) {
ALL_EVENTS.forEach( unbinder );
} else if(eventType in EVENTS) {
EVENTS[eventType].forEach( unbinder );
} else {
unbinder(eventType);
}
}
};
}(window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment