-
-
Save Fedik/63e32d747b356c975f8d to your computer and use it in GitHub Desktop.
Element event monitor, similar to Web Inspector's `monitorEvents`
This file contains hidden or 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
(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