How to hook on library function (Golden Layout) and call additional methods - javascript

I'm using a library called Golden Layout, it has a function called destroy which will close all the application window, on window close or refesh
I need to add additional method to the destroy function. I need to removeall the localstorage aswell.
How do i do it ? Please help
Below is the plugin code.
lm.LayoutManager = function( config, container ) {
....
destroy: function() {
if( this.isInitialised === false ) {
return;
}
this._onUnload();
$( window ).off( 'resize', this._resizeFunction );
$( window ).off( 'unload beforeunload', this._unloadFunction );
this.root.callDownwards( '_$destroy', [], true );
this.root.contentItems = [];
this.tabDropPlaceholder.remove();
this.dropTargetIndicator.destroy();
this.transitionIndicator.destroy();
this.eventHub.destroy();
this._dragSources.forEach( function( dragSource ) {
dragSource._dragListener.destroy();
dragSource._element = null;
dragSource._itemConfig = null;
dragSource._dragListener = null;
} );
this._dragSources = [];
},
I can access the destroy method in the component like this
this.layout = new GoldenLayout(this.config, this.layoutElement.nativeElement);
this.layout.destroy();`
My code
#HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
var originalDestroy = this.layout.destroy;
this.layout.destroy = function() {
// Call the original
originalDestroy.apply(this, arguments);
localStorage.clear();
};
}

Looking at the documentation, GoldenLayout offers an itemDestroyed event you could hook to do your custom cleanup. The description is:
Fired whenever an item gets destroyed.
If for some reason you can't, the general answer is that you can easily wrap the function:
var originalDestroy = this.layout.destroy;
this.layout.destroy = function() {
// Call the original
originalDestroy.apply(this, arguments);
// Do your additional work here
};
You may be able to do this for all instances if necessary by modifying GoldenLayout.prototype:
var originalDestroy = GoldenLayout.prototype.destroy;
GoldenLayout.prototype.destroy = function() {
// Call the original
originalDestroy.apply(this, arguments);
// Do your additional work here
};
Example:
// Stand-in for golden laout
function GoldenLayout() {
}
GoldenLayout.prototype.destroy = function() {
console.log("Standard functionality");
};
// Your override:
var originalDestroy = GoldenLayout.prototype.destroy;
GoldenLayout.prototype.destroy = function() {
// Call the original
originalDestroy.apply(this, arguments);
// Do your additional work here
console.log("Custom functionality");
};
// Use
var layout = new GoldenLayout();
layout.destroy();

Hooking into golden layout is the intended purpose for the events.
As briefly touched on by #T.J. Crowder, there is the itemDestroyed event which is called when an item in the layout is destroyed.
You can just listen for this event like such:
this.layout.on('itemDestroyed', function() {
localStorage.clear();
})
However, this event is called every time anything is destroyed, and propagates down the tree, even just by closing a tab. This means that if you call destroy on the layout root, you will get an event for every RowOrColumn, Stack and Component
I would recommend to check the item passed into the event and ignore if not the main window (root item)
this.layout.on('itemDestroyed', function(item) {
if (item.type === "root") {
localStorage.clear();
}
})

Related

Javascript: managing clicks from one instance to the next

I am very new to Javascript.
I am trying to write this baby jQuery plugin that I will use to make dropdown lists. What I am failing to achieve (beyond things that I do not notice) is to neatly exit or deactivate my active instance as I click on another instance. I tried to illustrate my problem in the following fiddle (keeping the structure I am using):
https://jsfiddle.net/andinse/m0kwfj9d/23/
What the Javascript looks like:
$(document).ready(function() {
$.fn.activator = function() {
var Activator = function(el) {
this.html = $('html');
this.el = el;
this.is_active = false;
this.initialize();
};
Activator.prototype.initialize = function() {
var self = this;
self.el.on('click', function(e) {
if (self.is_active === false) {
self.toggle('activate');
} else {
self.toggle('deactivate');
}
});
};
Activator.prototype.toggle = function(action) {
var self = this;
if (action === 'activate') {
console.log('activating ' + self.el[0].className);
self.is_active = true;
self.el.addClass('red');
self.html.on('click', function(e) {
if (e.target != self.el[0]) {
self.toggle('deactivate');
}
});
}
if (action === 'deactivate') {
console.log('deactivating ' + self.el[0].className);
self.is_active = false;
self.el.removeClass('red');
self.html.off('click');
}
};
if (typeof this !== 'undefined') {
var activator = new Activator(this);
}
return this;
};
$('.a').activator();
$('.b').activator();
$('.c').activator();
});
My idea was:
To watch for clicks on html as soon as the instance is active (thus ready to be deactivated). On click, to check if the event.target is the same as the active instance. If not, to deactivate this instance.
To stop watching for clicks as soon as the instance is inactive. So that we're not doing unnecessary work.
When it is set like this, it seems to work for only one cycle (click on A activates A then click on B activates B and deactivates A then click on C activates C but doesn't deactivate B).
If I get rid of the "self.html.off('click')" it seems to work kind of ok but if I look at the log I can see the "toggle" function is sometimes triggered multiple times per click. There must be a cleaner way.
Any piece of help greatly appreciated.
With your logic, when clicking any element you should deactivate any current activated element. Either do it globally:
$('.your_activation_class').removeClass('.your_activation_class');
or in some parent scope
$('some_parent_selector .your_activation_class').removeClass('.your_activation_class');

jQuery plugin instances variable with event handlers

I am writing my first jQuery plugin which is a tree browser. It shall first show the top level elements and on click go deeper and show (depending on level) the children in a different way.
I got this up and running already. But now I want to implement a "back" functionality and for this I need to store an array of clicked elements for each instance of the tree browser (if multiple are on the page).
I know that I can put instance private variables with "this." in the plugin.
But if I assign an event handler of the onClick on a topic, how do I get this instance private variable? $(this) is referencing the clicked element at this moment.
Could please anyone give me an advise or a link to a tutorial how to get this done?
I only found tutorial for instance specific variables without event handlers involved.
Any help is appreciated.
Thanks in advance.
UPDATE: I cleaned out the huge code generation and kept the logical structure. This is my code:
(function ($) {
$.fn.myTreeBrowser = function (options) {
clickedElements = [];
var defaults = {
textColor: "#000",
backgroundColor: "#fff",
fontSize: "1em",
titleAttribute: "Title",
idAttribute: "Id",
parentIdAttribute: "ParentId",
levelAttribute: "Level",
treeData: {}
};
var opts = $.extend({}, $.fn.myTreeBrowser.defaults, options);
function getTreeData(id) {
if (opts.data) {
$.ajax(opts.data, { async: false, data: { Id: id } }).success(function (resultdata) {
opts.treeData = resultdata;
});
}
}
function onClick() {
var id = $(this).attr('data-id');
var parentContainer = getParentContainer($(this));
handleOnClick(parentContainer, id);
}
function handleOnClick(parentContainer, id) {
if (opts.onTopicClicked) {
opts.onTopicClicked(id);
}
clickedElements.push(id);
if (id) {
var clickedElement = $.grep(opts.treeData, function (n, i) { return n[opts.idAttribute] === id })[0];
switch (clickedElement[opts.levelAttribute]) {
case 1:
renderLevel2(parentContainer, clickedElement);
break;
case 3:
renderLevel3(parentContainer, clickedElement);
break;
default:
debug('invalid level element clicked');
}
} else {
renderTopLevel(parentContainer);
}
}
function getParentContainer(elem) {
return $(elem).parents('div.myBrowserContainer').parents()[0];
}
function onBackButtonClick() {
clickedElements.pop(); // remove actual element to get the one before
var lastClickedId = clickedElements.pop();
var parentContainer = getParentContainer($(this));
handleOnClick(parentContainer, lastClickedId);
}
function renderLevel2(parentContainer, selectedElement) {
$(parentContainer).html('');
var browsercontainer = $('<div>').addClass('myBrowserContainer').appendTo(parentContainer);
//... rendering the div ...
// for example like this with a onClick handler
var div = $('<div>').attr('data-id', element[opts.idAttribute]).addClass('fct-bs-col-md-4 pexSubtopic').on('click', onClick).appendTo(subtopicList);
// ... rendering the tree
var backButton = $('<button>').addClass('btn btn-default').text('Back').appendTo(browsercontainer);
backButton.on('click', onBackButtonClick);
}
function renderLevel3(parentContainer, selectedElement) {
$(parentContainer).html('');
var browsercontainer = $('<div>').addClass('myBrowserContainer').appendTo(parentContainer);
//... rendering the div ...
// for example like this with a onClick handler
var div = $('<div>').attr('data-id', element[opts.idAttribute]).addClass('fct-bs-col-md-4 pexSubtopic').on('click', onClick).appendTo(subtopicList);
// ... rendering the tree
var backButton = $('<button>').addClass('btn btn-default').text('Back').appendTo(browsercontainer);
backButton.on('click', onBackButtonClick);
}
function renderTopLevel(parentContainer) {
parentContainer.html('');
var browsercontainer = $('<div>').addClass('fct-page-pa fct-bs-container-fluid pexPAs myBrowserContainer').appendTo(parentContainer);
// rendering the top level display
}
getTreeData();
//top level rendering! Lower levels are rendered in event handlers.
$(this).each(function () {
renderTopLevel($(this));
});
return this;
};
// Private function for debugging.
function debug(debugText) {
if (window.console && window.console.log) {
window.console.log(debugText);
}
};
}(jQuery));
Just use one more class variable and pass this to it. Usually I call it self. So var self = this; in constructor of your plugin Class and you are good to go.
Object oriented way:
function YourPlugin(){
var self = this;
}
YourPlugin.prototype = {
constructor: YourPlugin,
clickHandler: function(){
// here the self works
}
}
Check this Fiddle
Or simple way of passing data to eventHandler:
$( "#foo" ).bind( "click", {
self: this
}, function( event ) {
alert( event.data.self);
});
You could use the jQuery proxy function:
$(yourElement).bind("click", $.proxy(this.yourFunction, this));
You can then use this in yourFunction as the this in your plugin.

JS Hooking Custom Events

I have a client side script for my .NET control. The script hooks all the :checkbox items to trigger an event called OnOptionItemSelected.
function ControlScript() {
this.OnOptionItemSelected = function (e) { /* do something */ }
this.Configure = function () {
// hook change event of items in the input control
$('#' + this.ControlID).find(":radio, :checkbox")
.on("change", this, this.OnOptionItemSelected);
}
}
(Some pieces of code removed)
In another place on the page, I get the client side script for a particular control and need to hook the OnOptionItemSelected event. How would I hook this event?
var script = GetScriptForControl(ID);
if (script)
// hook script.OnOptionItemSelected to a custom function ????
I will suppose that the GetScriptForControl return a instance of ControlScript. So what i would do is:
if(script) {
oldOptionItemSelected = script.OnOptionItemSelected
script.OnOptionItemSelected = function(ev) {
/* before OptionItemSelected code HERE */
oldOptionItemSelected.call(script,ev);
/* after OptionItemSelected code HERE */
};
/* rebind the events */
script.Configure();
}
I actually found an answer that better suits my needs:
function ControlClientSide()
{
this.CheckBoxClicked = function() { }
this.Configure = function() {
$('#checkBox100').change(function() { $(this).triggerHandler("CheckBoxClicked"); }.bind(this));
};
this.Configure();
};
var x = new ControlClientSide();
$(x).on("CheckBoxClicked", function() { alert( this.constructor.name + ' Hi'); })
.on("CheckBoxClicked", function() { alert( this.constructor.name + ' Hi2'); });
The only thing I cant figure out is how to get "this" to be the checkbox in the "CheckBoxClicked" event handlers. Currently it is set to the ControlClientSide function.
See example: http://jsfiddle.net/KC5RH/3/

backbone.js do something when event (vent) is complete?

$('button').click(function(){
App.vent.trigger("box:change");
});
App.BoxView = Backbone.View.extend({
initialize: function(options) {
this.listenTo( App.vent, "box:change", this.alter ); // animate, etc.
},
...
});
I have a main view, in wich i wish to do some changes when (and/or):
the event is processed by all my boxes
all my boxes done with some animations
can't wrap my head around this(long work day)...
please help =)
what is the better practice?
i'm looking for something like this:
App.MainView = Backbone.View.extend({
initialize: function(options) {
// when all the events are complete
this.listenTo( App.vent, "box:change" ).onComplete( this.rearrange_stuff );
// when all the animations are complete
this.listenTo( App.animationBuffer, "box:fadeOut" ).onComplete( this.rearrange_stuff );
},
...
});
update:
and what if I have a long chain of events - complete - events - complete (not loop) in my application, what is the better way to set this queue?
with jquery I found promise, just need to figure-out how i apply this to all my views..
http://api.jquery.com/promise/
(update)
For now, I've done it this way...
http://jsfiddle.net/Antonimo/YyxQ3/2/
App.vent = _.extend(Backbone.Events, {
promise: function(name){
if(typeof this._bills[name] === "undefined"){
this._bills[name] = 0;
} else {
this._bills[name] ++;
}
},
keepPromise: function(name){
var that = this;
setTimeout( function(){
if(typeof that._checks[name] === "undefined"){
that._checks[name] = 0;
} else {
that._checks[name] ++;
}
if(typeof that._bills[name] !== "undefined"){
if( that._checks[name] >= that._bills[name] ){
that._checks[name] = 0; // reset
that._bills[name] = 0; // reset
that.trigger(name); // emit event
}
}
}, 30);
},
_bills: {},
_checks: {}
});
// usage:
alter: function() {
App.vent.promise('some:event');
// Animate, or not..
App.vent.pay('some:event');
},
I was looking for a solution to this and found this plugin to Backbone that adds a "triggerThen" method to Backbone.Events and other Backbone objects which allows you to trigger an event and then call a function after all of the event listeners have completed.
https://github.com/bookshelf/trigger-then
It would be nice if there was an official Backbone solution to this though that used promises throughout the Backbone.Events framework.

How do you log all events fired by an element in jQuery?

I'd like to see all the events fired by an input field as a user interacts with it. This includes stuff like:
Clicking on it.
Clicking off it.
Tabbing into it.
Tabbing away from it.
Ctrl+C and Ctrl+V on the keyboard.
Right click -> Paste.
Right click -> Cut.
Right click -> Copy.
Dragging and dropping text from another application.
Modifying it with Javascript.
Modifying it with a debug tool, like Firebug.
I'd like to display it using console.log. Is this possible in Javascript/jQuery, and if so, how do I do it?
I have no idea why no-one uses this... (maybe because it's only a webkit thing)
Open console:
monitorEvents(document.body); // logs all events on the body
monitorEvents(document.body, 'mouse'); // logs mouse events on the body
monitorEvents(document.body.querySelectorAll('input')); // logs all events on inputs
$(element).on("click mousedown mouseup focus blur keydown change",function(e){
console.log(e);
});
That will get you a lot (but not all) of the information on if an event is fired... other than manually coding it like this, I can't think of any other way to do that.
There is a nice generic way using the .data('events') collection:
function getEventsList($obj) {
var ev = new Array(),
events = $obj.data('events'),
i;
for(i in events) { ev.push(i); }
return ev.join(' ');
}
$obj.on(getEventsList($obj), function(e) {
console.log(e);
});
This logs every event that has been already bound to the element by jQuery the moment this specific event gets fired. This code was pretty damn helpful for me many times.
Btw: If you want to see every possible event being fired on an object use firebug: just right click on the DOM element in html tab and check "Log Events". Every event then gets logged to the console (this is sometimes a bit annoying because it logs every mouse movement...).
$('body').on("click mousedown mouseup focus blur keydown change mouseup click dblclick mousemove mouseover mouseout mousewheel keydown keyup keypress textInput touchstart touchmove touchend touchcancel resize scroll zoom focus blur select change submit reset",function(e){
console.log(e);
});
I know the answer has already been accepted to this, but I think there might be a slightly more reliable way where you don't necessarily have to know the name of the event beforehand. This only works for native events though as far as I know, not custom ones that have been created by plugins. I opted to omit the use of jQuery to simplify things a little.
let input = document.getElementById('inputId');
Object.getOwnPropertyNames(input)
.filter(key => key.slice(0, 2) === 'on')
.map(key => key.slice(2))
.forEach(eventName => {
input.addEventListener(eventName, event => {
console.log(event.type);
console.log(event);
});
});
I hope this helps anyone who reads this.
EDIT
So I saw another question here that was similar, so another suggestion would be to do the following:
monitorEvents(document.getElementById('inputId'));
Old thread, I know. I needed also something to monitor events and wrote this very handy (excellent) solution. You can monitor all events with this hook (in windows programming this is called a hook). This hook does not affects the operation of your software/program.
In the console log you can see something like this:
Explanation of what you see:
In the console log you will see all events you select (see below "how to use") and shows the object-type, classname(s), id, <:name of function>, <:eventname>.
The formatting of the objects is css-like.
When you click a button or whatever binded event, you will see it in the console log.
The code I wrote:
function setJQueryEventHandlersDebugHooks(bMonTrigger, bMonOn, bMonOff)
{
jQuery.fn.___getHookName___ = function()
{
// First, get object name
var sName = new String( this[0].constructor ),
i = sName.indexOf(' ');
sName = sName.substr( i, sName.indexOf('(')-i );
// Classname can be more than one, add class points to all
if( typeof this[0].className === 'string' )
{
var sClasses = this[0].className.split(' ');
sClasses[0]='.'+sClasses[0];
sClasses = sClasses.join('.');
sName+=sClasses;
}
// Get id if there is one
sName+=(this[0].id)?('#'+this[0].id):'';
return sName;
};
var bTrigger = (typeof bMonTrigger !== "undefined")?bMonTrigger:true,
bOn = (typeof bMonOn !== "undefined")?bMonOn:true,
bOff = (typeof bMonOff !== "undefined")?bMonOff:true,
fTriggerInherited = jQuery.fn.trigger,
fOnInherited = jQuery.fn.on,
fOffInherited = jQuery.fn.off;
if( bTrigger )
{
jQuery.fn.trigger = function()
{
console.log( this.___getHookName___()+':trigger('+arguments[0]+')' );
return fTriggerInherited.apply(this,arguments);
};
}
if( bOn )
{
jQuery.fn.on = function()
{
if( !this[0].__hooked__ )
{
this[0].__hooked__ = true; // avoids infinite loop!
console.log( this.___getHookName___()+':on('+arguments[0]+') - binded' );
$(this).on( arguments[0], function(e)
{
console.log( $(this).___getHookName___()+':'+e.type );
});
}
var uResult = fOnInherited.apply(this,arguments);
this[0].__hooked__ = false; // reset for another event
return uResult;
};
}
if( bOff )
{
jQuery.fn.off = function()
{
if( !this[0].__unhooked__ )
{
this[0].__unhooked__ = true; // avoids infinite loop!
console.log( this.___getHookName___()+':off('+arguments[0]+') - unbinded' );
$(this).off( arguments[0] );
}
var uResult = fOffInherited.apply(this,arguments);
this[0].__unhooked__ = false; // reset for another event
return uResult;
};
}
}
Examples how to use it:
Monitor all events:
setJQueryEventHandlersDebugHooks();
Monitor all triggers only:
setJQueryEventHandlersDebugHooks(true,false,false);
Monitor all ON events only:
setJQueryEventHandlersDebugHooks(false,true,false);
Monitor all OFF unbinds only:
setJQueryEventHandlersDebugHooks(false,false,true);
Remarks/Notice:
Use this for debugging only, turn it off when using in product final
version
If you want to see all events, you have to call this function
directly after jQuery is loaded
If you want to see only less events, you can call the function on the time you need it
If you want to auto execute it, place ( )(); around function
Hope it helps! ;-)
https://github.com/robertleeplummerjr/wiretap.js
new Wiretap({
add: function() {
//fire when an event is bound to element
},
before: function() {
//fire just before an event executes, arguments are automatic
},
after: function() {
//fire just after an event executes, arguments are automatic
}
});
Just add this to the page and no other worries, will handle rest for you:
$('input').live('click mousedown mouseup focus keydown change blur', function(e) {
console.log(e);
});
You can also use console.log('Input event:' + e.type) to make it easier.
STEP 1: Check the events for an HTML element on the developer console:
STEP 2: Listen to the events we want to capture:
$(document).on('ch-ui-container-closed ch-ui-container-opened', function(evt){
console.log(evt);
});
Good Luck...
I recently found and modified this snippet from an existing SO post that I have not been able to find again but I've found it very useful
// specify any elements you've attached listeners to here
const nodes = [document]
// https://developer.mozilla.org/en-US/docs/Web/Events
const logBrowserEvents = () => {
const AllEvents = {
AnimationEvent: ['animationend', 'animationiteration', 'animationstart'],
AudioProcessingEvent: ['audioprocess'],
BeforeUnloadEvent: ['beforeunload'],
CompositionEvent: [
'compositionend',
'compositionstart',
'compositionupdate',
],
ClipboardEvent: ['copy', 'cut', 'paste'],
DeviceLightEvent: ['devicelight'],
DeviceMotionEvent: ['devicemotion'],
DeviceOrientationEvent: ['deviceorientation'],
DeviceProximityEvent: ['deviceproximity'],
DragEvent: [
'drag',
'dragend',
'dragenter',
'dragleave',
'dragover',
'dragstart',
'drop',
],
Event: [
'DOMContentLoaded',
'abort',
'afterprint',
'beforeprint',
'cached',
'canplay',
'canplaythrough',
'change',
'chargingchange',
'chargingtimechange',
'checking',
'close',
'dischargingtimechange',
'downloading',
'durationchange',
'emptied',
'ended',
'error',
'fullscreenchange',
'fullscreenerror',
'input',
'invalid',
'languagechange',
'levelchange',
'loadeddata',
'loadedmetadata',
'noupdate',
'obsolete',
'offline',
'online',
'open',
'open',
'orientationchange',
'pause',
'play',
'playing',
'pointerlockchange',
'pointerlockerror',
'ratechange',
'readystatechange',
'reset',
'seeked',
'seeking',
'stalled',
'submit',
'success',
'suspend',
'timeupdate',
'updateready',
'visibilitychange',
'volumechange',
'waiting',
],
FocusEvent: [
'DOMFocusIn',
'DOMFocusOut',
'Unimplemented',
'blur',
'focus',
'focusin',
'focusout',
],
GamepadEvent: ['gamepadconnected', 'gamepaddisconnected'],
HashChangeEvent: ['hashchange'],
KeyboardEvent: ['keydown', 'keypress', 'keyup'],
MessageEvent: ['message'],
MouseEvent: [
'click',
'contextmenu',
'dblclick',
'mousedown',
'mouseenter',
'mouseleave',
'mousemove',
'mouseout',
'mouseover',
'mouseup',
'show',
],
// https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
MutationNameEvent: ['DOMAttributeNameChanged', 'DOMElementNameChanged'],
MutationEvent: [
'DOMAttrModified',
'DOMCharacterDataModified',
'DOMNodeInserted',
'DOMNodeInsertedIntoDocument',
'DOMNodeRemoved',
'DOMNodeRemovedFromDocument',
'DOMSubtreeModified',
],
OfflineAudioCompletionEvent: ['complete'],
OtherEvent: ['blocked', 'complete', 'upgradeneeded', 'versionchange'],
UIEvent: [
'DOMActivate',
'abort',
'error',
'load',
'resize',
'scroll',
'select',
'unload',
],
PageTransitionEvent: ['pagehide', 'pageshow'],
PopStateEvent: ['popstate'],
ProgressEvent: [
'abort',
'error',
'load',
'loadend',
'loadstart',
'progress',
],
SensorEvent: ['compassneedscalibration', 'Unimplemented', 'userproximity'],
StorageEvent: ['storage'],
SVGEvent: [
'SVGAbort',
'SVGError',
'SVGLoad',
'SVGResize',
'SVGScroll',
'SVGUnload',
],
SVGZoomEvent: ['SVGZoom'],
TimeEvent: ['beginEvent', 'endEvent', 'repeatEvent'],
TouchEvent: [
'touchcancel',
'touchend',
'touchenter',
'touchleave',
'touchmove',
'touchstart',
],
TransitionEvent: ['transitionend'],
WheelEvent: ['wheel'],
}
const RecentlyLoggedDOMEventTypes = {}
Object.keys(AllEvents).forEach((DOMEvent) => {
const DOMEventTypes = AllEvents[DOMEvent]
if (Object.prototype.hasOwnProperty.call(AllEvents, DOMEvent)) {
DOMEventTypes.forEach((DOMEventType) => {
const DOMEventCategory = `${DOMEvent} ${DOMEventType}`
nodes.forEach((node) => {
node.addEventListener(
DOMEventType,
(e) => {
if (RecentlyLoggedDOMEventTypes[DOMEventCategory]) return
RecentlyLoggedDOMEventTypes[DOMEventCategory] = true
// NOTE: throttle continuous events
setTimeout(() => {
RecentlyLoggedDOMEventTypes[DOMEventCategory] = false
}, 1000)
const isActive = e.target === document.activeElement
// https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement
const hasActiveElement = document.activeElement !== document.body
const msg = [
DOMEventCategory,
'target:',
e.target,
...(hasActiveElement
? ['active:', document.activeElement]
: []),
]
if (isActive) {
console.info(...msg)
}
},
true,
)
})
})
}
})
}
logBrowserEvents()
// export default logBrowserEvents
function bindAllEvents (el) {
for (const key in el) {
if (key.slice(0, 2) === 'on') {
el.addEventListener(key.slice(2), e => console.log(e.type));
}
}
}
bindAllEvents($('.yourElement'))
This uses a bit of ES6 for prettiness, but can easily be translated for legacy browsers as well. In the function attached to the event listeners, it's currently just logging out what kind of event occurred but this is where you could print out additional information, or using a switch case on the e.type, you could only print information on specific events
Here is a non-jquery way to monitor events in the console with your code and without the use of monitorEvents() because that only works in Chrome Developer Console. You can also choose to not monitor certain events by editing the no_watch array.
function getEvents(obj) {
window["events_list"] = [];
var no_watch = ['mouse', 'pointer']; // Array of event types not to watch
var no_watch_reg = new RegExp(no_watch.join("|"));
for (var prop in obj) {
if (prop.indexOf("on") === 0) {
prop = prop.substring(2); // remove "on" from beginning
if (!prop.match(no_watch_reg)) {
window["events_list"].push(prop);
window.addEventListener(prop, function() {
console.log(this.event); // Display fired event in console
} , false);
}
}
}
window["events_list"].sort(); // Alphabetical order
}
getEvents(document); // Put window, document or any html element here
console.log(events_list); // List every event on element
How to listen for all events on an Element (Vanilla JS)
For all native events, we can retrieve a list of supported events by iterating over the target.onevent properties and installing our listener for all of them.
for (const key in target) {
if(/^on/.test(key)) {
const eventType = key.substr(2);
target.addEventListener(eventType, listener);
}
}
The only other way that events are emitted which I know of is via EventTarget.dispatchEvent, which every Node and thefore every Element inherits.
To listen for all these manually triggered events, we can proxy the dispatchEvent method globally and install our listener just-in-time for the event whose name we just saw ✨ ^^
const dispatchEvent_original = EventTarget.prototype.dispatchEvent;
EventTarget.prototype.dispatchEvent = function (event) {
if (!alreadyListenedEventTypes.has(event.type)) {
target.addEventListener(event.type, listener, ...otherArguments);
alreadyListenedEventTypes.add(event.type);
}
dispatchEvent_original.apply(this, arguments);
};
🔥 function snippet 🔥
function addEventListenerAll(target, listener, ...otherArguments) {
// install listeners for all natively triggered events
for (const key in target) {
if (/^on/.test(key)) {
const eventType = key.substr(2);
target.addEventListener(eventType, listener, ...otherArguments);
}
}
// dynamically install listeners for all manually triggered events, just-in-time before they're dispatched ;D
const dispatchEvent_original = EventTarget.prototype.dispatchEvent;
function dispatchEvent(event) {
target.addEventListener(event.type, listener, ...otherArguments); // multiple identical listeners are automatically discarded
dispatchEvent_original.apply(this, arguments);
}
EventTarget.prototype.dispatchEvent = dispatchEvent;
if (EventTarget.prototype.dispatchEvent !== dispatchEvent) throw new Error(`Browser is smarter than you think!`);
}
// usage example
const input = document.querySelector('input');
addEventListenerAll(input, (evt) => {
console.log(evt.type);
});
input.focus();
input.click();
input.dispatchEvent(new Event('omg!', { bubbles: true }));
// usage example with `useCapture`
// (also receives `bubbles: false` events, but in reverse order)
addEventListenerAll(
input,
(evt) => { console.log(evt.type); },
true
);
document.body.dispatchEvent(new Event('omfggg!', { bubbles: false }));

Categories

Resources