public
Last active

Element event monitor, similar to Web Inspector's `monitorEvents`

  • Download Gist
EventMonitor.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
(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));

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.