Merge pull request #40 from michgeek/master

Add support for namespaced Vuex actions
pull/52/head
Metin Seylan 8 years ago committed by GitHub
commit 1d662700bf

@ -6,7 +6,7 @@
<img id="dependency_badge" src="https://www.versioneye.com/javascript/metinseylan:vue-socket.io/2.0.1/badge.svg" alt="Dependency Badge" rel="nofollow">
<a href="https://www.npmjs.com/package/vue-socket.io"><img src="https://img.shields.io/npm/l/vue-socket.io.svg" alt="License"></a>
socket.io implemantation for Vuejs 2 and Vuex
socket.io implementation for Vuejs 2 and Vuex
## Install
@ -66,7 +66,13 @@ delete this.$options.sockets.event_name;
```
#### Vuex Store integration
Example store, socket mutations always have "SOCKET_" prefix
Socket **mutations** always have `SOCKET_` prefix.
Socket **actions** always have `socket_` prefix and the socket event name is `camelCased` (ex. `SOCKET_USER_MESSAGE` => `socket_userMessage`)
You can use either one or another or both in your store. Namespaced modules are supported.
``` js
import Vue from 'vue'
import Vuex from 'vuex'
@ -87,8 +93,16 @@ export default new Vuex.Store({
}
},
actions: {
otherAction: ({ commit, dispatch, state }, type) => {
otherAction: (context, type) => {
return true;
},
socket_userMessage: (context, message) => {
context.dispatch('newMessage', message);
context.commit('NEW_MESSAGE_RECEIVED', message);
if (message.is_important) {
context.dispatch('alertImportantMessage', message);
}
...
}
}
})

2
dist/build.js vendored

File diff suppressed because one or more lines are too long

@ -21,8 +21,7 @@ export default class{
this.Socket.onevent = (packet) => {
Emitter.emit(packet.data[0], packet.data[1]);
if(this.store) this.commitStore('SOCKET_'+packet.data[0], packet.data[1])
if(this.store) this.passToStore('SOCKET_'+packet.data[0], packet.data[1])
};
let _this = this;
@ -31,25 +30,30 @@ export default class{
.forEach((value) => {
_this.Socket.on(value, (data) => {
Emitter.emit(value, data);
if(_this.store) _this.commitStore('SOCKET_'+value.toUpperCase(), data)
if(_this.store) _this.passToStore('SOCKET_'+value, data)
})
})
}
commitStore(type, payload){
passToStore(event, payload){
if(!event.startsWith('SOCKET_')) return
if(type.split('_')[0].toUpperCase() === 'SOCKET'){
for(let namespaced in this.store._mutations) {
let mutation = namespaced.split('/').pop()
if(mutation === event.toUpperCase()) this.store.commit(namespaced, payload)
}
for (let namespaced in this.store._mutations) {
let mutation = namespaced.split('/').pop()
for(let namespaced in this.store._actions) {
let action = namespaced.split('/').pop()
if (mutation === type)
this.store.commit(namespaced, payload)
}
if(!action.startsWith('socket_')) continue
}
let camelcased = 'socket_'+event
.replace('SOCKET_', '')
.replace(/^([A-Z])|[\W\s_]+(\w)/g, (match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase())
if(action === camelcased) this.store.dispatch(namespaced, payload)
}
}
}

Loading…
Cancel
Save