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

class WebSocketClient extends Observable {

  constructor() {
    super();
  }

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

}

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

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

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

Alexander Bazo committed
35 36 37 38 39 40
function onMessage(event) {
  let dataEvent = new DataEvent(event.data);
  this.notifyAll(dataEvent);
}

export default WebSocketClient;