INF310: Modern JS, Fall 2017 > Data Structures > Events
DOM Events

DOM events represent interactions from the user or the browser APIs.

Listening for events
  const button = document.getElementById('btn1');

  button.addEventListener('click', function (clickEvent) {
    console.log({ element: this, clickEvent });
Triggering Events
  const button = document.getElementById('btn1');

  var aClick = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true

Event propagation / delegation

Event bubbling means that event targeted at child nodes will execute the event handlers of the chain of parent nodes.

  <h1>Select your favorite color:</h1>
  <ul id="colors">
        (event) => console.log(
Custom Events in Browser
  // Listening for events on a DOM element (e.g. document)
    function ({ detail }) => console.log(detail)

  // Trigger the event
  const myEvent = new CustomEvent(
    { detail: 'custom properties' }

Events in NodeJS
  const EventEmitter = require('events').EventEmitter;
  const source = new EventEmitter();

  source.on('eventName', callback);
  source.once('eventName', callback);

  source.emit('eventName', payload);
  websocket.on('connection', socket => {
    socket.on('message', console.log);

Events are a great mechanism to implement various patterns.


An event with a single producer and multiple consumers.

  // these can be defined in different parts of the system
  btn.on('click', updateUI);
  btn.on('click', updateDB);
  btn.on('click', logsAndMetrics);

An event with a multiple producers and (possibly) a single consumers.

  // multiple players fire the same event
  lobby.emit('ready', player);

  //the lobby module pairs players in games
  lobby.on('ready', startWithTwoPlayers);

A "hub" with multiple topics. Events are a natural implementation of the pub/sub pattern.

It allows us to decouple the producers and consumers (publishers and subscribers) of a messaging system.

  topics.on('new-items', handleNewItem);
  topics.on('my-message', handleMyMessage);
  topics.on('item-order', handleItemOrder);

  topics.emit('new-item', { name: "Laptop", price: 873.50 });
  topics.emit('item-order', { item, client });