I’m developing a web application and I need to capture all events of all elements, I write a code myself, but I need you lovely experts to improve my code’s performance as much as you can.
// Create mouse event callbacks and an array to store callbacks,
// This array is to prevent creation of callback functions multiple times
var mouseEventCallbacks = {};
var mouseEvents = [
'mouseover',
'mouseout',
'mousedown',
'mouseup',
'click',
'mousemove',
'contextmenu',
'dblclick',
'mousewheel'
];
function mouseEventCallback(eventType){
if(!mouseEventCallbacks[eventType])
mouseEventCallbacks[eventType] = function(event) {
self.port.emit('new-event', {
x: event.pageX + window.pageXOffset,
y: event.pageY + window.pageYOffset
},{
type: eventType
});
}
return mouseEventCallbacks[eventType];
}
// Attach all events to all elements
var elems = window.document.querySelectorAll('*');
for(var j = 0, s = elems.length; j < s; j++) {
attachMouseEvents(elems[j]);
}
function attachMouseEvents(element){
for(var k = 0, s = mouseEvents.length; k < s; k++){
element.addEventListener(mouseEvents[k],
mouseEventCallback(mouseEvents[k]),
false);
}
}
Instead of attaching event handler to each element, use event delegation. When event is triggered, it bubles in the DOM up to the body (or the first element that handle the event), so you han handle all events in the body’s event handler. Then you have the
event.targetproperty with the reference to the DOM element that actually triggered itP.S. I’ve linked jQuery documentation, but it’s general advice and it’s not just about using jQuery