gazeclient.js 1.97 KB
Newer Older
Alexander Bazo committed
1
(function () {
2
  'use strict';
Alexander Bazo committed
3

4
  /* eslint-env browser */
Alexander Bazo committed
5

6
  class Event {
Alexander Bazo committed
7

8 9 10 11
    constructor(type, data) {
      this.type = type;
      this.data = data;
    }
Alexander Bazo committed
12

13
  }
Alexander Bazo committed
14

15
  class Observable {
Alexander Bazo committed
16

17 18 19
    constructor() {
      this.listeners = {};
    }
Alexander Bazo committed
20

21 22 23 24 25 26
    addEventListener(type, callback) {
      if (this.listeners[type] === undefined) {
        this.listeners[type] = [];
      }
      this.listeners[type].push(callback);
    }
Alexander Bazo committed
27

28 29 30 31 32 33 34 35
    notifyAll(event) {
      let listeners = this.listeners[event.type];
      if (listeners) {
        for (let i = 0; i < listeners.length; i++) {
          listeners[i](event);
        }
      }
    }
Alexander Bazo committed
36

37
  }
Alexander Bazo committed
38

39
  /* eslint-env browser */
Alexander Bazo committed
40

41 42 43 44 45
  class GazeDataEvent extends Event {
    constructor(data) {
      super("gazeDataAvailable", data);
    }
  }
Alexander Bazo committed
46

47 48 49 50 51
  class ConnectionEvent extends Event {
    constructor() {
      super("connected");
    }
  }
Alexander Bazo committed
52

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
  class WebSocketClient extends Observable {

    constructor() {
      super();
    }

    connect(url) {

      this.ws = new WebSocket(url);
      this.ws.onopen = onOpen.bind(this);
      this.ws.onmessage = onMessage.bind(this);
    }

  }

  function onOpen() {
    let connectionEvent = new ConnectionEvent();
    this.notifyAll(connectionEvent);
  }

  function onMessage(event) {
    let gazeEvent = new GazeDataEvent(event.data);
    this.notifyAll(gazeEvent);
  }

  /* eslint-env browser */

  class GazeClient extends Observable {

    constructor() {
      super();
    }

    connect(url) {
      this.url = url;
      this.client = new WebSocketClient();
      this.client.addEventListener("connected", this.onConnected.bind(this));
      this.client.addEventListener("gazeDataAvailable", this.onGazeDataAvailable
        .bind(this));
      this.client.connect(url);
    }

    onOpen() {
      this.client.send("hello server");
    }

    onConnected(event) {
      // TODO: Implement event broadcasting
    }

    onGazeDataAvailable(event) {
      this.notifyAll(event);
    }

  }

  window.GazeClient = GazeClient;
Alexander Bazo committed
110 111

}());