WebSocketClient.js 1 KB
Newer Older
Alexander Bazo committed
1
import Observable from "../utils/Observable.js";
2 3 4
import { ConnectionOpenedEvent, ConnectionClosedEvent, ConnectionErrorEvent,
  DataEvent } from "./Events.js";
import GazeData from "../data/GazeData.js";
Alexander Bazo committed
5 6 7 8 9 10 11 12 13 14

class WebSocketClient extends Observable {

  constructor() {
    super();
  }

  connect(url) {
    this.ws = new WebSocket(url);
    this.ws.onopen = onOpen.bind(this);
Alexander Bazo committed
15 16
    this.ws.onclose = onClose.bind(this);
    this.ws.onerror = onError.bind(this);
Alexander Bazo committed
17 18 19 20 21 22 23 24 25 26
    this.ws.onmessage = onMessage.bind(this);
  }

}

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

Alexander Bazo committed
27 28 29 30 31 32 33 34 35 36
function onClose() {
  let connectionEvent = new ConnectionClosedEvent();
  this.notifyAll(connectionEvent);
}

function onError() {
  let connectionEvent = new ConnectionErrorEvent();
  this.notifyAll(connectionEvent);
}

Alexander Bazo committed
37
function onMessage(event) {
38 39
  let data = GazeData.fromDataString(event.data),
    dataEvent = new DataEvent(data);
Alexander Bazo committed
40 41 42 43
  this.notifyAll(dataEvent);
}

export default WebSocketClient;