mirror of
https://github.com/MetinSeylan/Vue-Socket.io.git
synced 2025-04-16 15:21:28 +02:00
on event dispatch store option
This commit is contained in:
parent
51f5a95014
commit
8de127066d
2 changed files with 31 additions and 7 deletions
|
@ -3,11 +3,11 @@ import Emitter from './Emitter'
|
|||
|
||||
export default {
|
||||
|
||||
install(Vue, connection, store){
|
||||
install(Vue, connection, store, useActions = false){
|
||||
|
||||
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;
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@ import Socket from 'socket.io-client'
|
|||
|
||||
export default class{
|
||||
|
||||
constructor(connection, store) {
|
||||
constructor(connection, store, useActions) {
|
||||
|
||||
if(typeof connection == 'string'){
|
||||
this.Socket = Socket(connection);
|
||||
|
@ -11,7 +11,10 @@ export default class{
|
|||
this.Socket = connection
|
||||
}
|
||||
|
||||
if(store) this.store = store;
|
||||
if(store) {
|
||||
this.store = store;
|
||||
this.useActions = useActions;
|
||||
}
|
||||
|
||||
this.onEvent()
|
||||
|
||||
|
@ -21,17 +24,27 @@ 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.useActions
|
||||
? this.dispatchStore('SOCKET_'+packet.data[0], packet.data[1])
|
||||
: this.commitStore('SOCKET_'+packet.data[0], packet.data[1])
|
||||
|
||||
};
|
||||
|
||||
let _this = this;
|
||||
|
||||
["connect", "error", "disconnect", "reconnect", "reconnect_attempt", "reconnecting", "reconnect_error", "reconnect_failed", "connect_error", "connect_timeout", "connecting", "ping", "pong"]
|
||||
.forEach((value) => {
|
||||
_this.Socket.on(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…
Add table
Reference in a new issue