Client: Implement event system (#4)
This commit is contained in:
parent
36ba716ad8
commit
ceca822f97
4 changed files with 81 additions and 7 deletions
|
|
@ -1,7 +1,18 @@
|
|||
"use strict";
|
||||
|
||||
class Client {
|
||||
/**
|
||||
* Client class that implements the InstantChat protocol using WebSockets.
|
||||
*
|
||||
* Dispatches the following events which can be subscribed/unsubscribed using .on() and .off():
|
||||
* - initialized: Connection to server has been established and initialized, ready to send messages.
|
||||
* - disconnected: Connection has been closed.
|
||||
* - connectionError: Some connection error occurred.
|
||||
* - receivedMessage: Chat message has been received. Data: object {from: 'username', text: 'text'}
|
||||
*/
|
||||
class Client extends EventDispatcher {
|
||||
constructor(wsUri) {
|
||||
super();
|
||||
|
||||
this.wsUri = wsUri;
|
||||
|
||||
// Create WebSocket and set internal callbacks
|
||||
|
|
@ -16,17 +27,17 @@ class Client {
|
|||
// Internal WebSocket event handlers
|
||||
_onSocketOpen(evt) {
|
||||
console.log("Connected to " + this.wsUri);
|
||||
|
||||
// Send init command containing chat ID and nickname
|
||||
this.sendInit();
|
||||
}
|
||||
|
||||
_onSocketClose(evt) {
|
||||
console.log("Connection closed (code " + evt.code + ").");
|
||||
this.dispatch("disconnected");
|
||||
}
|
||||
|
||||
_onSocketError(evt) {
|
||||
console.error("Connection error: ", evt);
|
||||
this.dispatch("connectionError");
|
||||
}
|
||||
|
||||
_onSocketMessage(evt) {
|
||||
|
|
@ -76,16 +87,19 @@ class Client {
|
|||
const msg = JSON.parse(msgString);
|
||||
|
||||
switch (msg.type) {
|
||||
// Response to "init" command
|
||||
// Response to 'init' command (doesn't have much content, I guess)
|
||||
case "init":
|
||||
// TODO
|
||||
console.log("Got init response: ", msg);
|
||||
this.dispatch("initialized");
|
||||
break;
|
||||
|
||||
// Incoming chat message
|
||||
case "message":
|
||||
// TODO
|
||||
console.log("Got message event: from '" + msg.from + "', text '" + msg.text + "'");
|
||||
console.log("Received chat message from '" + msg.from + "', text '" + msg.text + "'");
|
||||
this.dispatch("receivedMessage", {
|
||||
from: msg.from,
|
||||
text: msg.text,
|
||||
});
|
||||
break;
|
||||
|
||||
// TODO Topic change, user join/leave, error, ...
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue