Skip to content

Instantly share code, notes, and snippets.

@byronmejia
Created May 22, 2016 13:31
Show Gist options
  • Save byronmejia/dd156f13957e03d6f63b50282374a05b to your computer and use it in GitHub Desktop.
Save byronmejia/dd156f13957e03d6f63b50282374a05b to your computer and use it in GitHub Desktop.
// -------------------- Constants --------------------
const CMD_TGL = 'toggle';
const CMD_ON = 'H';
const CMD_OFF = 'L';
const MSG_CMD = 'command';
const MSG_CHAT = 'message';
const PRT_LED = 'led';
// These are the different types of messages so far
function CommandMessage( option ) {
this.messageType = option.messageType || MSG_CMD;
this.command = option.command || CMD_TGL;
this.part = option.part || PRT_LED;
}
function ChatMessage( option ) {
this.messageType = option.messageType || MSG_CHAT;
this.text = option.text || 'Hello World';
}
// This factory builds cool shit
function MessageFactory() {
MessageFactory.prototype.createMsg = function createMessage( options ) {
var parentClass = null;
switch(options.messageType){
case MSG_CMD:
parentClass = CommandMessage;
break;
case MSG_CHAT:
parentClass = ChatMessage;
break;
default:
break;
}
if(parentClass === null) return false;
return new parentClass(options);
}
}
var msgFactory = new MessageFactory();
// On-Click events that will use the factory
function ledON() {
var ledMessage = msgFactory.createMsg({
messageType : MSG_CMD,
command : CMD_ON,
part : PRT_LED
} );
console.log(ledMessage)
exampleSocket.send(JSON.stringify(ledMessage))
}
function ledOFF() {
var ledMessage = msgFactory.createMsg({
messageType : MSG_CMD,
command : CMD_OFF,
part : PRT_LED
} );
console.log(ledMessage);
exampleSocket.send(JSON.stringify(ledMessage))
}
function sendChat(text) {
var chat = msgFactory.createMsg({
messageType : MSG_CHAT,
text : text
} );
console.log(chat);
exampleSocket.send(JSON.stringify(chat))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment