100 lines
2.5 KiB
JavaScript
100 lines
2.5 KiB
JavaScript
// import Vue from 'vue'
|
|
// import Vuex from 'vuex'
|
|
import { createStore } from "vuex";
|
|
|
|
// Vue.use(Vuex)
|
|
|
|
// root state object.
|
|
// each Vuex instance is just a single state tree.
|
|
const state = {
|
|
count: 0,
|
|
webSocket: WebSocket
|
|
}
|
|
|
|
|
|
|
|
// mutations are operations that actually mutate the state.
|
|
// each mutation handler gets the entire state tree as the
|
|
// first argument, followed by additional payload arguments.
|
|
// mutations must be synchronous and can be recorded by plugins
|
|
// for debugging purposes.
|
|
const mutations = {
|
|
increment(state) {
|
|
state.count++
|
|
},
|
|
decrement(state) {
|
|
state.count--
|
|
},
|
|
reconnect() {
|
|
state.webSocket = new WebSocket("ws://tropicananass.ovh:8080");
|
|
|
|
state.webSocket.onopen = function (event) {
|
|
console.log(`[open] ws: Connection established: ${event.code}`);
|
|
};
|
|
|
|
state.webSocket.onmessage = function (event) {
|
|
console.log(`[message] ws: Data received from server: ${event.data}`);
|
|
let message = event.data.split(":");
|
|
let command = message[0];
|
|
let payload = message[1];
|
|
console.log(command + ", " + payload);
|
|
switch (command) {
|
|
case 'm':
|
|
document.getElementById("mode-input").elements["mode-selection"][payload].checked = true;
|
|
break;
|
|
|
|
default:
|
|
break;
|
|
}
|
|
};
|
|
|
|
state.webSocket.webSocketonclose = function (event) {
|
|
if (event.wasClean) {
|
|
console.log(`[close] ws: Connection closed cleanly, code=${event.code} reason=${event.reason}`);
|
|
} else {
|
|
console.log('[close] ws: Connection died');
|
|
}
|
|
};
|
|
|
|
state.webSocket.onerror = function (error) {
|
|
console.log(`[error] ws: ${error.message}`);
|
|
};
|
|
}
|
|
}
|
|
|
|
// actions are functions that cause side effects and can involve
|
|
// asynchronous operations.
|
|
const actions = {
|
|
increment: ({ commit }) => commit('increment'),
|
|
decrement: ({ commit }) => commit('decrement'),
|
|
incrementIfOdd({ commit, state }) {
|
|
if ((state.count + 1) % 2 === 0) {
|
|
commit('increment')
|
|
}
|
|
},
|
|
incrementAsync({ commit }) {
|
|
return new Promise((resolve) => {
|
|
setTimeout(() => {
|
|
commit('increment')
|
|
resolve()
|
|
}, 1000)
|
|
})
|
|
}
|
|
}
|
|
|
|
// getters are functions.
|
|
const getters = {
|
|
evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd',
|
|
isConnected: state => state.webSocket.readyState == WebSocket.OPEN
|
|
}
|
|
|
|
// A Vuex instance is created by combining the state, mutations, actions,
|
|
// and getters.
|
|
const store = createStore({
|
|
state,
|
|
getters,
|
|
actions,
|
|
mutations
|
|
})
|
|
|
|
export default store |