Skip to content

Commit

Permalink
Merge pull request #59 from OmgImAlexis/master
Browse files Browse the repository at this point in the history
add support for custom mutation name
  • Loading branch information
weglov authored Sep 12, 2018
2 parents 432b1de + a5e3c86 commit 2835a4b
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 2 deletions.
62 changes: 61 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -173,6 +172,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.
Expand Down
7 changes: 6 additions & 1 deletion src/Observer.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export default class {
this.connect(connectionUrl, opts)

if (opts.store) { this.store = opts.store }
if (opts.mutations) { this.mutations = opts.mutations }
this.onEvent()
}

Expand Down Expand Up @@ -91,6 +92,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)
}
}
}

0 comments on commit 2835a4b

Please sign in to comment.