Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(): Multiple connections #288

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 105 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ new Vue({
debug|Boolean|`false`|Optional|Enable logging for debug
connection|String/Socket.io-client|`null`|Required|Websocket server url or socket.io-client instance
vuex.store|Vuex|`null`|Optional|Vuex store instance
vuex.actionPrefix|String|`null`|Optional|Prefix for emitting server side vuex actions
vuex.mutationPrefix|String |`null`|Optional|Prefix for emitting server side vuex mutations
vuex.actionPrefix|String/Function|`null`|Optional|Prefix for emitting server side vuex actions
vuex.mutationPrefix|String/Function|`null`|Optional|Prefix for emitting server side vuex mutations

#### 🌈 Component Level Usage

Expand Down Expand Up @@ -180,6 +180,109 @@ export default new Vuex.Store({
})
```

#### 🏆 Connection Namespace

``` javascript
import Vue from 'vue'
import store from './store'
import App from './App.vue'
import VueSocketIO from 'vue-socket.io'

const app = SocketIO('http://localhost:1090', {
useConnectionNamespace: true,
});

const chat = SocketIO('http://localhost:1090/chat', {
useConnectionNamespace: true,
autoConnect: false,
});

Vue.use(new VueSocketIO({
debug: true,
connection: {
app,
chat
},
vuex: {
store,
actionPrefix: eventName => {
return (`SOCKET_` + eventName).toUpperCase();
},
mutationPrefix: eventName => {
return (`SOCKET_` + eventName).toUpperCase();
},
},
options: { path: "/my-app/" } //Optional options
}))

new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
```

Then use it like this:

``` javascript
new Vue({
sockets: {
app: {
connect: function() {
console.log('socket connected');
},
customEmit: function(data) {
console.log('this method was fired by the socket server');
},
},
chat: {
connect: function() {
console.log('socket connected');
},
customEmit: function(data) {
console.log('this method was fired by the socket server');
},
},
},
methods: {
clickAppButton: function(data) {
// $socket.app is socket.io-client instance
this.$socket.app.emit('emit_method', data);
},
clickChatButton: function(data) {
// $socket.chat is socket.io-client instance
this.$socket.chat.emit('emit_method', data);
},
},
});

```

vuex

``` javascript
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
state: {},
mutations: {
"<MUTATION_PREFIX>_<MY_NAMESPACE>_<EVENT_NAME>"() {
// do something
}
},
actions: {
"<ACTION_PREFIX>_<MY_NAMESPACE>_<EVENT_NAME>"() {
// do something
}
}
})
```



## Stargazers over time

[![Stargazers over time](https://starcharts.herokuapp.com/MetinSeylan/Vue-Socket.io.svg)](https://starcharts.herokuapp.com/MetinSeylan/Vue-Socket.io)
Expand Down
8 changes: 4 additions & 4 deletions dist/vue-socketio.js

Large diffs are not rendered by default.

14 changes: 10 additions & 4 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,24 @@ declare module 'vue/types/options' {
}
}

type prefixFunc = (eventName: string) => string;

type connectionSocket = {
[key: string]: SocketIOClient.Socket
}

export interface VueSocketOptions {
debug?: boolean;
connection: string | SocketIOClient.Socket,
connection: string | SocketIOClient.Socket | connectionSocket,
vuex?: {
store?: Store<any>,
actionPrefix?: string,
mutationPrefix?: string,
actionPrefix?: string | prefixFunc,
mutationPrefix?: string | prefixFunc,
options?: {
useConnectionNamespace?: boolean
}
},
// type declarations for optional options
// type declarations for optional options
options?:{
path?: string;
}
Expand Down
221 changes: 99 additions & 122 deletions src/emitter.js
Original file line number Diff line number Diff line change
@@ -1,136 +1,113 @@
import Logger from './logger';

export default class EventEmitter{

constructor(vuex = {}){
Logger.info(vuex ? `Vuex adapter enabled` : `Vuex adapter disabled`);
Logger.info(vuex.mutationPrefix ? `Vuex socket mutations enabled` : `Vuex socket mutations disabled`);
Logger.info(vuex ? `Vuex socket actions enabled` : `Vuex socket actions disabled`);
this.store = vuex.store;
this.actionPrefix = vuex.actionPrefix ? vuex.actionPrefix : 'SOCKET_';
this.mutationPrefix = vuex.mutationPrefix;
this.listeners = new Map();
export default class EventEmitter {
constructor(vuex = {}) {
Logger.info(vuex ? `Vuex adapter enabled` : `Vuex adapter disabled`);
Logger.info(vuex.mutationPrefix ? `Vuex socket mutations enabled` : `Vuex socket mutations disabled`);
Logger.info(vuex ? `Vuex socket actions enabled` : `Vuex socket actions disabled`);
this.store = vuex.store;
this.actionPrefix = vuex.actionPrefix ? vuex.actionPrefix : 'SOCKET_';
this.mutationPrefix = vuex.mutationPrefix ? vuex.mutationPrefix : 'SOCKET_';
this.listeners = new Map();
}

/**
* register new event listener with vuejs component instance
* @param event
* @param callback
* @param component
*/
addListener(event, callback, component) {
if (typeof callback === 'function') {
if (!this.listeners.has(event)) this.listeners.set(event, []);
this.listeners.get(event).push({ callback, component });

Logger.info(`#${event} subscribe, component: ${component.$options.name}`);
} else {
throw new Error(`callback must be a function`);
}

/**
* register new event listener with vuejs component instance
* @param event
* @param callback
* @param component
*/
addListener(event, callback, component){

if(typeof callback === 'function'){

if (!this.listeners.has(event)) this.listeners.set(event, []);
this.listeners.get(event).push({ callback, component });

Logger.info(`#${event} subscribe, component: ${component.$options.name}`);

} else {

throw new Error(`callback must be a function`);

}

}

/**
* remove a listenler
* @param event
* @param component
*/
removeListener(event, component) {
if (this.listeners.has(event)) {
const listeners = this.listeners.get(event).filter(listener => listener.component !== component);

if (listeners.length > 0) {
this.listeners.set(event, listeners);
} else {
this.listeners.delete(event);
}

Logger.info(`#${event} unsubscribe, component: ${component.$options.name}`);
}

/**
* remove a listenler
* @param event
* @param component
*/
removeListener(event, component){

if(this.listeners.has(event)){

const listeners = this.listeners.get(event).filter(listener => (
listener.component !== component
));

if (listeners.length > 0) {
this.listeners.set(event, listeners);
} else {
this.listeners.delete(event);
}

Logger.info(`#${event} unsubscribe, component: ${component.$options.name}`);

}

}

/**
* broadcast incoming event to components
* @param event
* @param args
*/
emit(event, args) {
if (this.listeners.has(event)) {
Logger.info(`Broadcasting: #${event}, Data:`, args);

this.listeners.get(event).forEach(listener => {
listener.callback.call(listener.component, args);
});
}

/**
* broadcast incoming event to components
* @param event
* @param args
*/
emit(event, args){

if(this.listeners.has(event)){

Logger.info(`Broadcasting: #${event}, Data:`, args);

this.listeners.get(event).forEach((listener) => {
listener.callback.call(listener.component, args);
});

}

if(event !== 'ping' && event !== 'pong') {
this.dispatchStore(event, args);
if (event !== 'ping' && event !== 'pong') {
this.dispatchStore(event, args);
}
}

/**
* dispatching vuex actions
* @param event
* @param args
*/
dispatchStore(event, args) {
if (this.store && this.store._actions) {
let prefixedEvent;
if (typeof this.actionPrefix === 'function') {
prefixedEvent = this.actionPrefix(event);
} else {
prefixedEvent = this.actionPrefix + event;
}

for (let key in this.store._actions) {
let action = key.split('/').pop();

if (action === prefixedEvent) {
Logger.info(`Dispatching Action: ${key}, Data:`, args);

this.store.dispatch(key, args);
}

}
}

if (this.store && this.store._mutations) {
let prefixedEvent;
if (typeof this.mutationPrefix === 'function') {
prefixedEvent = this.mutationPrefix(event);
} else {
prefixedEvent = (this.mutationPrefix || '') + event;
}

/**
* dispatching vuex actions
* @param event
* @param args
*/
dispatchStore(event, args){

if(this.store && this.store._actions){

let prefixed_event = this.actionPrefix + event;

for (let key in this.store._actions) {

let action = key.split('/').pop();

if(action === prefixed_event) {

Logger.info(`Dispatching Action: ${key}, Data:`, args);

this.store.dispatch(key, args);

}

}
for (let key in this.store._mutations) {
let mutation = key.split('/').pop();

if(this.mutationPrefix) {

let prefixed_event = this.mutationPrefix + event;

for (let key in this.store._mutations) {

let mutation = key.split('/').pop();

if(mutation === prefixed_event) {

Logger.info(`Commiting Mutation: ${key}, Data:`, args);

this.store.commit(key, args);

}

}

}
if (mutation === prefixedEvent) {
Logger.info(`Commiting Mutation: ${key}, Data:`, args);

this.store.commit(key, args);
}

}
}

}
}
}
Loading