Skip to content

Instantly share code, notes, and snippets.

@slorber
Created March 6, 2017 16:00
Show Gist options
  • Save slorber/b1c0ffef56abd449c05476b5c609a36e to your computer and use it in GitHub Desktop.
Save slorber/b1c0ffef56abd449c05476b5c609a36e to your computer and use it in GitHub Desktop.
// Logs all calls to preventDefault / stopPropagation in an user-friendly way
if ( process.env.NODE_ENV !== "production" ) {
(function monkeyPatchEventMethods() {
const logEventMethodCall = (event,methodName) => {
const MinimumMeaninfulSelectors = 3; // how much meaningful items we want in log message
const target = event.target;
const selector = (function computeSelector() {
const parentSelectors = [];
let node = target;
let minimumSelectors = 0;
do {
const meaningfulSelector = node.id ?
`#${node.id}` : node.classList.length > 0 ?
`.${Array.prototype.join.call(node.classList, '.')}` : undefined;
if ( meaningfulSelector ) minimumSelectors++;
const nodeSelector = `${node.tagName.toLowerCase()}${meaningfulSelector ? meaningfulSelector : ''}`;
parentSelectors.unshift(nodeSelector);
node = node.parentNode;
} while (node && node !== document && minimumSelectors < MinimumMeaninfulSelectors);
return parentSelectors.join(" > ");
})();
console.debug(`${event.type}.${methodName}() on ${selector}`,event);
};
const preventDefault = Event.prototype.preventDefault;
Event.prototype.preventDefault = function() {
logEventMethodCall(this,'preventDefault');
preventDefault.call(this);
};
const stopPropagation = Event.prototype.stopPropagation;
Event.prototype.stopPropagation = function() {
logEventMethodCall(this,'stopPropagation');
stopPropagation.call(this);
};
})();
}
@slorber
Copy link
Author

slorber commented Mar 6, 2017

thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment