on event dispatch store option

pull/36/head
Fakhreev Rafael 8 years ago
parent 51f5a95014
commit 8de127066d

@ -3,11 +3,11 @@ import Emitter from './Emitter'
export default { export default {
install(Vue, connection, store){ install(Vue, connection, store, useActions = false){
if(!connection) throw new Error("[Vue-Socket.io] cannot locate connection") if(!connection) throw new Error("[Vue-Socket.io] cannot locate connection")
let observer = new Observer(connection, store) let observer = new Observer(connection, store, useActions)
Vue.prototype.$socket = observer.Socket; Vue.prototype.$socket = observer.Socket;

@ -3,7 +3,7 @@ import Socket from 'socket.io-client'
export default class{ export default class{
constructor(connection, store) { constructor(connection, store, useActions) {
if(typeof connection == 'string'){ if(typeof connection == 'string'){
this.Socket = Socket(connection); this.Socket = Socket(connection);
@ -11,7 +11,10 @@ export default class{
this.Socket = connection this.Socket = connection
} }
if(store) this.store = store; if(store) {
this.store = store;
this.useActions = useActions;
}
this.onEvent() this.onEvent()
@ -21,17 +24,27 @@ export default class{
this.Socket.onevent = (packet) => { this.Socket.onevent = (packet) => {
Emitter.emit(packet.data[0], packet.data[1]); Emitter.emit(packet.data[0], packet.data[1]);
if(this.store) this.commitStore('SOCKET_'+packet.data[0], packet.data[1]) if(this.store)
this.useActions
? this.dispatchStore('SOCKET_'+packet.data[0], packet.data[1])
: this.commitStore('SOCKET_'+packet.data[0], packet.data[1])
}; };
let _this = this; let _this = this;
["connect", "error", "disconnect", "reconnect", "reconnect_attempt", "reconnecting", "reconnect_error", "reconnect_failed", "connect_error", "connect_timeout", "connecting", "ping", "pong"] ["connect", "error", "disconnect", "reconnect", "reconnect_attempt", "reconnecting", "reconnect_error", "reconnect_failed", "connect_error", "connect_timeout", "connecting", "ping", "pong"]
.forEach((value) => { .forEach((value) => {
_this.Socket.on(value, (data) => { _this.Socket.on(value, (data) => {
Emitter.emit(value, data); Emitter.emit(value, data);
if(_this.store) _this.commitStore('SOCKET_'+value.toUpperCase(), data) if(_this.store) {
const toCamelCase = (str) => str.split('_')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join('')
_this.useActions
? _this.dispatchStore('socket' + toCamelCase(value), data)
: _this.commitStore('SOCKET_' + value.toUpperCase(), data)
}
}) })
}) })
} }
@ -48,4 +61,15 @@ export default class{
} }
dispatchStore(type, payload){
if(type.search(/socket/) === 0){
if(this.store._actions[type])
this.store.dispatch(type, payload)
}
}
} }

Loading…
Cancel
Save