From a5e3c863a5a2157667a8124917e9095684f6165b Mon Sep 17 00:00:00 2001 From: Alexis Tyler Date: Tue, 12 Jun 2018 15:46:29 +0930 Subject: [PATCH] add support for custom mutation name --- README.md | 62 ++++++++++++++++++++++++++++++++++++++++++++++++- src/Observer.js | 7 +++++- 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 15f6565..8012be3 100755 --- a/README.md +++ b/README.md @@ -37,7 +37,6 @@ import VueNativeSock from 'vue-native-websocket' Vue.use(VueNativeSock, 'ws://localhost:9090', { protocol: 'my-protocol' }) ``` - Optionally enable JSON message passing: ``` js @@ -165,6 +164,67 @@ export default new Vuex.Store({ }) ``` +##### With custom mutation names + +``` js +// store.js +import Vue from 'vue' +import Vuex from 'vuex' + +Vue.use(Vuex); + +export default new Vuex.Store({ + state: { + socket: { + isConnected: false, + message: '', + reconnectError: false, + } + }, + mutations:{ + SOCKET_ONOPEN (state, event) { + state.socket.isConnected = true + }, + SOCKET_ONCLOSE (state, event) { + state.socket.isConnected = false + }, + SOCKET_ONERROR (state, event) { + console.error(state, event) + }, + // default handler called for all methods + SOCKET_ONMESSAGE (state, message) { + state.socket.message = message + }, + // mutations for reconnect methods + SOCKET_RECONNECT(state, count) { + console.info(state, count) + }, + SOCKET_RECONNECT_ERROR(state) { + state.socket.reconnectError = true; + }, + } +}) + +// index.js +import store from './store' + +const mutations = { + SOCKET_ONOPEN: '✅ Socket connected!', + SOCKET_ONCLOSE: '❌ Socket disconnected!', + SOCKET_ONERROR: '❌ Socket Error!!!', + SOCKET_ONMESSAGE: 'Websocket message received', + SOCKET_RECONNECT: 'Websocket reconnected', + SOCKET_RECONNECT_ERROR: 'Websocket is having issues reconnecting..' +}; + +Vue.use(VueNativeSock, 'ws://localhost:9090', { + store: store, + format: 'json', + mutations: mutations +}) +``` + + ##### With `format: 'json'` enabled All data passed through the websocket is expected to be JSON. diff --git a/src/Observer.js b/src/Observer.js index 17c3c5c..f6e8220 100755 --- a/src/Observer.js +++ b/src/Observer.js @@ -15,6 +15,7 @@ export default class { this.connect(connectionUrl, opts) if (opts.store) { this.store = opts.store } + if (opts.mutations) { this.mutations = opts.mutations } this.onEvent() } @@ -74,6 +75,10 @@ export default class { target = [msg.namespace || '', msg.action].filter((e) => !!e).join('/') } } - this.store[method](target, msg) + if (this.mutations) { + this.store[this.mutations[method] || method](target, msg) + } else { + this.store[method](target, msg) + } } }