Skip to content

Instantly share code, notes, and snippets.

@ilyar
Last active January 1, 2019 13:26
Show Gist options
  • Select an option

  • Save ilyar/d604843aae847c0ecaba36b61f22578a to your computer and use it in GitHub Desktop.

Select an option

Save ilyar/d604843aae847c0ecaba36b61f22578a to your computer and use it in GitHub Desktop.
JavaScript notes

JavaScript notes

Listen for all events

/**
 * @param {Object} obj
 * @param {Array} typeEvents
 */
function addLogEvent(obj, typeEvents) {
  console.log('addEventListener for event:', typeEvents);
  typeEvents.forEach(typeEvent => {
    obj.addEventListener(typeEvent, event => {
      console.log(event.type, event.timeStamp, event);
    });
  });
}

/**
 * @param {Object} obj
 * @param {Array} filter
 */
function logEvents(obj, filter = []) {
  let typeEvents = ['DOMContentLoaded'];
  const matchFilter = prop =>
    (filter.length !== 0 && filter.find(pattern => prop.search(pattern) !== -1)) ||
    filter.length === 0;

  for (let prop in obj) {
    if (prop.search('on') === 0 && matchFilter(prop)) {
      typeEvents.push(prop.slice(2));
    }
  }
  addLogEvent(obj, typeEvents);
}

logEvents(window, ['load']);

Based on answer from @RomanBekkiev, but as @jeremywoertink mentioned any other events are also possible. TODO see https://github.com/EventEmitter2/EventEmitter2

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