Obserwator w ES6

Poniżej przykład implementacji Obserwatora w ES6.

class SimpleEventer {

  constructor() {
    this.simpleEventerListeners = {};
  }

  on(type, listener) {
    if (typeof this.simpleEventerListeners[type] === 'undefined') {
      this.simpleEventerListeners[type] = [];
    }

    this.simpleEventerListeners[type].push(listener);
  }

  fire(type, target = this) {
    let
      event = {},
      listeners;

    if (typeof type === 'string') {
      event = {type: type};
    } else {
      throw new Error('Wrong event type name.');
    }
    if (!event.target) {
      event.target = target;
    }

    listeners = this.simpleEventerListeners[event.type];

    if (listeners instanceof Array) {
      for (let i = 0, len = listeners.length; i < len; i++) {
        listeners[i].call(this, event);
      }
    }
  }

  off(type, listener) {
    let simpleEventerListeners = this.simpleEventerListeners[type];
    if (simpleEventerListeners instanceof Array) {
      for (let i = 0, len = simpleEventerListeners.length; i < len; i++) {
        if (simpleEventerListeners[i] === listener) {
          simpleEventerListeners.splice(i, 1);
          break;
        }
      }
    }
  }
}
class ComponentPopup {
  constructor() {

  }

  showPopup(text) {
    console.log(text);
  }
}
import SimpleEventer from 'simple-eventer';

export default class ComponentTimeout extends SimpleEventer {
  constructor() {
    super();

    this.initTimeout();
  }

  initTimeout() {
    setTimeout(() => {
      this.fire('afterTimeout');
    }, 2000);
  }
}
import ComponentPopup from '../components/componentPopup';
import ComponentTimeout from '../components/componentTimeout';

export class Mediator {
  constructor() {

    this.componentPopup = new ComponentPopup();
    this.componentTimeout = new ComponentTimeout();

    this.functionality1();
  }

  functionality1() {
    this.componentTimeout.on('afterTimeout', () => {
      this.componentPopup.showPopup('po timeoutce'); // po timeoutce
    });
  }
}
import Mediator from './patterns/observer';

function init() {
  let mediator = new Mediator();
}

$(document).ready(init);