Skip to content

Instantly share code, notes, and snippets.

@mohayonao
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save mohayonao/a985fd6098c24edcc68c to your computer and use it in GitHub Desktop.

Select an option

Save mohayonao/a985fd6098c24edcc68c to your computer and use it in GitHub Desktop.
let _dispatchers = {};
let _clientSocket = null;
export default class ActionDispatcher extends EventEmitter {
constructor() {
super();
_dispatchers[this.name || this.constructor.name] = this;
}
dispatch(action) {
if (_clientSocket) {
_clientSocket.emit("_dispatch", {
sender: this.name || this.constructor.name,
action: action,
});
} else {
this.emit("dispatch", action);
}
}
register(callback) {
this.on("dispatch", callback);
}
static setSocket(socket, mode) {
if (mode === ActionDispatcher.SERVER_MODE) {
socket.on("_dispatch", ({ sender, action }) => {
let target = _dispatchers[sender];
if (target) {
target.emit("dispatch", action);
}
});
}
if (mode === ActionDispatcher.CLIENT_MODE) {
_clientSocket = socket;
}
}
}
ActionDispatcher.SERVER_MODE = "server";
ActionDispatcher.CLIENT_MODE = "client";
import ActionDispatcher from "../ActionDispatcher";
export class SampleActions extends ActionDispatcher {
bang() {
this.dispatch({
actionType: "bang",
});
}
hello(name) {
this.dispatch({
actionType: "hello",
text: `hello! ${name}`,
});
}
}
export default new SampleActions();
import SampleActions from "./actions/SampleActions";
import ActionDispatcher from "./ActionDispatcher";
let socket = window.io();
ActionDispatcher.setSocket(socket, ActionDispatcher.CLIENT_MODE);
import SampleActions from "./actions/SampleActions";
import ActionDispatcher from "./ActionDispatcher";
socketIO.on("connecting", (socket) => {
ActionDispatcher.setSocket(socket, ActionDispatcher.SERVER_MODE);
});
import SampleActions from "./actions/SampleActions";
import ActionDispatcher from "./ActionDispatcher";
import EventEmitter from "./EventEmitter";
let socket = new EventEmitter();
ActionDispatcher.setSocket(socket, ActionDispatcher.SERVER_MODE);
ActionDispatcher.setSocket(socket, ActionDispatcher.CLIENT_MODE);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment