mirror of
https://github.com/MetinSeylan/Vue-Socket.io.git
synced 2025-04-16 15:21:28 +02:00
Compare commits
No commits in common. "master" and "2.1.0" have entirely different histories.
20 changed files with 255 additions and 778 deletions
25
.gitignore
vendored
25
.gitignore
vendored
|
@ -1,23 +1,4 @@
|
|||
.DS_Store
|
||||
node_modules
|
||||
# dist
|
||||
|
||||
# local env files
|
||||
.env.local
|
||||
.env.*.local
|
||||
*.map
|
||||
|
||||
# Log files
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
package-lock.json
|
||||
|
||||
# Editor directories and files
|
||||
.bitmap
|
||||
.idea
|
||||
.vscode
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
node_modules/
|
||||
npm-debug.log
|
||||
.idea/
|
17
.npmignore
17
.npmignore
|
@ -1,17 +0,0 @@
|
|||
.DS_Store
|
||||
src/
|
||||
node_modules/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
*.map
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
.vscode
|
||||
.bitmap
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
.github/
|
7
LICENSE
7
LICENSE
|
@ -1,7 +0,0 @@
|
|||
Copyright 2018 Metin Seylan
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
223
README.md
Normal file → Executable file
223
README.md
Normal file → Executable file
|
@ -1,192 +1,99 @@
|
|||
<p align="center">
|
||||
<a href="https://github.com/MetinSeylan/Vue-Socket.io" target="_blank">
|
||||
<img width="250" src="https://raw.githubusercontent.com/MetinSeylan/Vue-Socket.io/master/docs/logo.png">
|
||||
</a>
|
||||
</p>
|
||||
# Vue-Socket.io
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/package/vue-socket.io"><img src="https://img.shields.io/npm/v/vue-socket.io.svg"/> <img src="https://img.shields.io/npm/dt/vue-socket.io.svg"/></a>
|
||||
<a href="https://github.com/vuejs/awesome-vue"><img src="https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg"/></a>
|
||||
<a href="https://vuejs.org/"><img src="https://img.shields.io/badge/vue-2.x-brightgreen.svg"/></a>
|
||||
<a href="http://packagequality.com/#?package=vue-socket.io"><img src="http://npm.packagequality.com/shield/vue-socket.io.svg"/></a>
|
||||
<a href="https://github.com/MetinSeylan/Vue-Socket.io/"><img src="https://img.shields.io/npm/l/vue-socket.io.svg"/></a>
|
||||
<a href="https://github.com/MetinSeylan/Vue-Socket.io/"><img src="https://img.shields.io/github/stars/MetinSeylan/Vue-Socket.io.svg"/></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://www.patreon.com/MetinSeylan">
|
||||
<img alt="Patreon" src="https://c5.patreon.com/external/logo/become_a_patron_button.png" height="50" />
|
||||
</a>
|
||||
</p>
|
||||
<p>Vue-Socket.io is a socket.io integration for Vuejs, easy to use, supporting Vuex and component level socket consumer managements.<p>
|
||||
[](https://www.npmjs.com/package/vue-socket.io)
|
||||

|
||||
<a href="https://www.npmjs.com/package/vue-socket.io"><img src="https://img.shields.io/npm/dt/vue-socket.io.svg" alt="Downloads"></a>
|
||||
<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>
|
||||
|
||||
###### Demo
|
||||
- <a href="http://metinseylan.com/vuesocketio/" target="_blank">Chat Application</a>
|
||||
- <a href="http://metinseylan.com" target="_blank">Car Tracking Application</a>
|
||||
<p>You can also check my other npm library <a href="https://github.com/MetinSeylan/Nestjs-OpenTelemetry">Nestjs OpenTelemetry</a></p>
|
||||
<p>
|
||||
are you looking for old documentation? <a href="https://github.com/MetinSeylan/Vue-Socket.io/blob/master/docs/OLD_README.md">it's here</a>
|
||||
</p>
|
||||
socket.io implemantation for Vuejs 2 and Vuex
|
||||
|
||||
## Install
|
||||
|
||||
#### 🚀 Installation
|
||||
``` bash
|
||||
npm install vue-socket.io --save
|
||||
```
|
||||
##### Using Connection String
|
||||
``` javascript
|
||||
import Vue from 'vue'
|
||||
import store from './store'
|
||||
import App from './App.vue'
|
||||
import VueSocketIO from 'vue-socket.io'
|
||||
|
||||
Vue.use(new VueSocketIO({
|
||||
debug: true,
|
||||
connection: 'http://metinseylan.com:1992',
|
||||
vuex: {
|
||||
store,
|
||||
actionPrefix: 'SOCKET_',
|
||||
mutationPrefix: 'SOCKET_'
|
||||
},
|
||||
options: { path: "/my-app/" } //Optional options
|
||||
}))
|
||||
|
||||
new Vue({
|
||||
router,
|
||||
store,
|
||||
render: h => h(App)
|
||||
}).$mount('#app')
|
||||
## Usage
|
||||
#### Configration
|
||||
Automaticly socket connect from url string
|
||||
``` js
|
||||
Vue.use(VueSocketio, 'http://socketserver.com:1923');
|
||||
```
|
||||
|
||||
##### Using socket.io-client Instance
|
||||
``` javascript
|
||||
import Vue from 'vue'
|
||||
import store from './store'
|
||||
import App from './App.vue'
|
||||
import VueSocketIO from 'vue-socket.io'
|
||||
import SocketIO from 'socket.io-client'
|
||||
|
||||
const options = { path: '/my-app/' }; //Options object to pass into SocketIO
|
||||
|
||||
Vue.use(new VueSocketIO({
|
||||
debug: true,
|
||||
connection: SocketIO('http://metinseylan.com:1992', options), //options object is Optional
|
||||
vuex: {
|
||||
store,
|
||||
actionPrefix: "SOCKET_",
|
||||
mutationPrefix: "SOCKET_"
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
new Vue({
|
||||
router,
|
||||
store,
|
||||
render: h => h(App)
|
||||
}).$mount('#app')
|
||||
Bind custom socket.io-client instance
|
||||
``` js
|
||||
Vue.use(VueSocketio, socketio('http://socketserver.com:1923'));
|
||||
```
|
||||
|
||||
**Parameters**|**Type's**|**Default**|**Required**|**Description**
|
||||
-----|-----|-----|-----|-----
|
||||
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
|
||||
Enable Vuex integration
|
||||
``` js
|
||||
import store from './yourstore'
|
||||
Vue.use(VueSocketio, socketio('http://socketserver.com:1923'), store);
|
||||
```
|
||||
|
||||
#### 🌈 Component Level Usage
|
||||
|
||||
<p>If you want to listen socket events from component side, you need to add `sockets` object in Vue component. After that every function will start to listen events, depends on object key</p>
|
||||
|
||||
``` javascript
|
||||
new Vue({
|
||||
sockets: {
|
||||
connect: function () {
|
||||
console.log('socket connected')
|
||||
},
|
||||
customEmit: function (data) {
|
||||
console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
|
||||
}
|
||||
#### On Vuejs instance usage
|
||||
``` js
|
||||
var vm = new Vue({
|
||||
sockets:{
|
||||
connect: function(){
|
||||
console.log('socket connected')
|
||||
},
|
||||
methods: {
|
||||
clickButton: function (data) {
|
||||
// $socket is socket.io-client instance
|
||||
this.$socket.emit('emit_method', data)
|
||||
}
|
||||
customEmit: function(val){
|
||||
console.log('this method fired by socket server. eg: io.emit("customEmit", data)')
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
clickButton: function(val){
|
||||
// $socket is socket.io-client instance
|
||||
this.$socket.emit('emit_method', val);
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
##### Dynamic Listeners
|
||||
|
||||
<p>If you need consuming events dynamically in runtime, you can use `subscribe` and `unsubscribe` methods in Vue component</p>
|
||||
|
||||
``` javascript
|
||||
this.sockets.subscribe('EVENT_NAME', (data) => {
|
||||
this.msg = data.message;
|
||||
});
|
||||
|
||||
this.sockets.unsubscribe('EVENT_NAME');
|
||||
```
|
||||
|
||||
##### Defining handlers for events with special characters
|
||||
|
||||
<p>If you want to handle 'kebab-case', or "event with space inside it" events, then you have to define it via the following way</p>
|
||||
|
||||
``` javascript
|
||||
export default {
|
||||
name: 'Test',
|
||||
sockets: {
|
||||
connect: function () {
|
||||
console.log('socket to notification channel connected')
|
||||
},
|
||||
},
|
||||
|
||||
data () {
|
||||
return {
|
||||
something: [
|
||||
// ... something here for the data if you need.
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
mounted () {
|
||||
this.$socket.subscribe("kebab-case", function(data) {
|
||||
console.log("This event was fired by eg. sio.emit('kebab-case')", data)
|
||||
})
|
||||
}
|
||||
#### Dynamic socket event listenlers
|
||||
Create new listenler
|
||||
``` js
|
||||
this.$options.sockets.event_name = (data) => {
|
||||
console.log(data)
|
||||
}
|
||||
```
|
||||
Remove exist listenler
|
||||
``` js
|
||||
delete this.$options.sockets.event_name;
|
||||
```
|
||||
|
||||
#### 🏆 Vuex Integration
|
||||
<p>When you set store parameter in installation, `Vue-Socket.io` will start sending events to Vuex store. If you set both prefix for vuex, you can use `actions` and `mutations` at the same time. But, best way to use is just `actions`</p>
|
||||
|
||||
``` javascript
|
||||
#### Vuex Store integration
|
||||
Example store, socket mutations always have "SOCKET_" prefix
|
||||
``` js
|
||||
import Vue from 'vue'
|
||||
import Vuex from 'vuex'
|
||||
|
||||
Vue.use(Vuex)
|
||||
Vue.use(Vuex);
|
||||
|
||||
export default new Vuex.Store({
|
||||
state: {},
|
||||
mutations: {
|
||||
"<MUTATION_PREFIX><EVENT_NAME>"() {
|
||||
// do something
|
||||
state: {
|
||||
connect: false,
|
||||
message: null
|
||||
},
|
||||
mutations:{
|
||||
SOCKET_CONNECT: (state, status ) => {
|
||||
state.connect = true;
|
||||
},
|
||||
SOCKET_USER_MESSAGE: (state, message) => {
|
||||
state.message = message;
|
||||
}
|
||||
},
|
||||
actions: {
|
||||
"<ACTION_PREFIX><EVENT_NAME>"() {
|
||||
// do something
|
||||
otherAction: ({ commit, dispatch, state }, type) => {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Stargazers over time
|
||||
## Example
|
||||
[Realtime Car Tracker System](http://metinseylan.com/)
|
||||
|
||||
[](https://starcharts.herokuapp.com/MetinSeylan/Vue-Socket.io)
|
||||
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/MetinSeylan/Vue-Socket.io" target="_blank">
|
||||
<img src="https://media.giphy.com/media/11jlnltQgUi2mQ/giphy.gif">
|
||||
</a>
|
||||
</p>
|
||||
[Simple Chat App](http://metinseylan.com/vuesocketio/)
|
||||
|
|
3
dist/build.js
vendored
Executable file
3
dist/build.js
vendored
Executable file
File diff suppressed because one or more lines are too long
1
dist/build.js.map
vendored
Executable file
1
dist/build.js.map
vendored
Executable file
File diff suppressed because one or more lines are too long
12
dist/vue-socketio.js
vendored
12
dist/vue-socketio.js
vendored
File diff suppressed because one or more lines are too long
|
@ -1,114 +0,0 @@
|
|||
# Vue-Socket.io
|
||||
|
||||
[](https://www.npmjs.com/package/vue-socket.io)
|
||||

|
||||
<a href="https://www.npmjs.com/package/vue-socket.io"><img src="https://img.shields.io/npm/dt/vue-socket.io.svg" alt="Downloads"></a>
|
||||
<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 implementation for Vuejs 2 and Vuex
|
||||
|
||||
## Install
|
||||
|
||||
``` bash
|
||||
npm install vue-socket.io --save
|
||||
```
|
||||
|
||||
## Usage
|
||||
#### Configuration
|
||||
Automatic socket connection from an URL string
|
||||
``` js
|
||||
import VueSocketio from 'vue-socket.io';
|
||||
Vue.use(VueSocketio, 'http://socketserver.com:1923');
|
||||
```
|
||||
|
||||
Bind custom socket.io-client instance
|
||||
``` js
|
||||
Vue.use(VueSocketio, socketio('http://socketserver.com:1923'));
|
||||
```
|
||||
|
||||
Enable Vuex integration
|
||||
``` js
|
||||
import store from './yourstore'
|
||||
Vue.use(VueSocketio, socketio('http://socketserver.com:1923'), store);
|
||||
```
|
||||
|
||||
#### On Vuejs instance usage
|
||||
``` js
|
||||
var vm = new Vue({
|
||||
sockets:{
|
||||
connect: function(){
|
||||
console.log('socket connected')
|
||||
},
|
||||
customEmit: function(val){
|
||||
console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
clickButton: function(val){
|
||||
// $socket is socket.io-client instance
|
||||
this.$socket.emit('emit_method', val);
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
#### Dynamic socket event listeners
|
||||
Create a new listener
|
||||
``` js
|
||||
this.$options.sockets.event_name = (data) => {
|
||||
console.log(data)
|
||||
}
|
||||
```
|
||||
Remove existing listener
|
||||
``` js
|
||||
delete this.$options.sockets.event_name;
|
||||
```
|
||||
|
||||
#### Vuex Store integration
|
||||
|
||||
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'
|
||||
|
||||
Vue.use(Vuex);
|
||||
|
||||
export default new Vuex.Store({
|
||||
state: {
|
||||
connect: false,
|
||||
message: null
|
||||
},
|
||||
mutations:{
|
||||
SOCKET_CONNECT: (state, status ) => {
|
||||
state.connect = true;
|
||||
},
|
||||
SOCKET_USER_MESSAGE: (state, message) => {
|
||||
state.message = message;
|
||||
}
|
||||
},
|
||||
actions: {
|
||||
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);
|
||||
}
|
||||
...
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Example
|
||||
[Realtime Car Tracker System](http://metinseylan.com/)
|
||||
|
||||
[Simple Chat App](http://metinseylan.com/vuesocketio/)
|
BIN
docs/logo.png
BIN
docs/logo.png
Binary file not shown.
Before Width: | Height: | Size: 39 KiB |
63
index.d.ts
vendored
63
index.d.ts
vendored
|
@ -1,63 +0,0 @@
|
|||
import SocketIOClient from "socket.io-client";
|
||||
import {
|
||||
DefaultComputed,
|
||||
DefaultData,
|
||||
DefaultMethods,
|
||||
DefaultProps,
|
||||
PropsDefinition,
|
||||
} from "vue/types/options";
|
||||
import { Vue } from "vue/types/vue";
|
||||
import { PluginFunction, PluginObject } from "vue";
|
||||
import { Store } from "vuex";
|
||||
|
||||
interface socketHandler<T> {
|
||||
(this: T, ...args: any[]): void
|
||||
}
|
||||
|
||||
interface Sockets<V> {
|
||||
[key: string]: socketHandler<V>
|
||||
}
|
||||
|
||||
declare module 'vue/types/vue' {
|
||||
interface Vue {
|
||||
$socket: SocketIOClient.Socket,
|
||||
sockets: {
|
||||
subscribe(eventName: string, handler: socketHandler<Vue>): void,
|
||||
unsubscribe(eventName: string): void,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
declare module 'vue/types/options' {
|
||||
interface ComponentOptions<
|
||||
V extends Vue,
|
||||
Data=DefaultData<V>,
|
||||
Methods=DefaultMethods<V>,
|
||||
Computed=DefaultComputed,
|
||||
PropsDef=PropsDefinition<DefaultProps>,
|
||||
Props=DefaultProps> {
|
||||
sockets?: Sockets<V>
|
||||
}
|
||||
}
|
||||
|
||||
export interface VueSocketOptions {
|
||||
debug?: boolean;
|
||||
connection: string | SocketIOClient.Socket,
|
||||
vuex?: {
|
||||
store?: Store<any>,
|
||||
actionPrefix?: string,
|
||||
mutationPrefix?: string,
|
||||
options?: {
|
||||
useConnectionNamespace?: boolean
|
||||
}
|
||||
},
|
||||
// type declarations for optional options
|
||||
options?:{
|
||||
path?: string;
|
||||
}
|
||||
}
|
||||
|
||||
export default class VueSocketIO<T> implements PluginObject<T> {
|
||||
constructor (options: VueSocketOptions);
|
||||
install: PluginFunction<T>
|
||||
}
|
26
package.json
Normal file → Executable file
26
package.json
Normal file → Executable file
|
@ -1,11 +1,10 @@
|
|||
{
|
||||
"name": "vue-socket.io",
|
||||
"author": "Metin Seylan <metinsyln@gmail.com>",
|
||||
"version": "3.0.10",
|
||||
"description": "socket.io implementation for Vue.js and Vuex",
|
||||
"main": "dist/vue-socketio.js",
|
||||
"version": "2.1.0",
|
||||
"description": "socket.io implemantation for vuejs and vuex",
|
||||
"main": "dist/build.js",
|
||||
"scripts": {
|
||||
"build": "webpack --mode=production --progress --hide-modules"
|
||||
"build": "webpack --progress --hide-modules"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
@ -23,22 +22,19 @@
|
|||
"vuex",
|
||||
"redux"
|
||||
],
|
||||
"author": "Metin Seylan",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/MetinSeylan/Vue-Socket.io/issues"
|
||||
},
|
||||
"homepage": "https://github.com/MetinSeylan/Vue-Socket.io",
|
||||
"homepage": "https://github.com/MetinSeylan/Vue-Socket.io#readme",
|
||||
"dependencies": {
|
||||
"socket.io-client": "^2.1.1"
|
||||
"socket.io-client": "^1.4.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.1.2",
|
||||
"@babel/plugin-proposal-class-properties": "^7.1.0",
|
||||
"@babel/plugin-transform-classes": "^7.1.0",
|
||||
"@babel/preset-env": "^7.1.0",
|
||||
"babel-loader": "^8.0.4",
|
||||
"cross-env": "^5.2.0",
|
||||
"webpack": "^4.23.1",
|
||||
"webpack-cli": "^3.1.2"
|
||||
"babel-cli": "^6.11.4",
|
||||
"babel-loader": "^6.2.5",
|
||||
"babel-preset-es2015": "^6.3.13",
|
||||
"webpack": "^2.2.0-rc.3"
|
||||
}
|
||||
}
|
||||
|
|
49
src/Emitter.js
Executable file
49
src/Emitter.js
Executable file
|
@ -0,0 +1,49 @@
|
|||
export default new class {
|
||||
constructor() {
|
||||
this.listeners = new Map();
|
||||
}
|
||||
|
||||
addListener(label, callback, vm) {
|
||||
if(typeof callback == 'function'){
|
||||
this.listeners.has(label) || this.listeners.set(label, []);
|
||||
this.listeners.get(label).push({callback: callback, vm: vm});
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
removeListener(label, callback, vm) {
|
||||
let listeners = this.listeners.get(label),
|
||||
index;
|
||||
|
||||
if (listeners && listeners.length) {
|
||||
index = listeners.reduce((i, listener, index) => {
|
||||
return (typeof listener.callback == 'function' && listener.callback === callback && listener.vm == vm) ?
|
||||
i = index :
|
||||
i;
|
||||
}, -1);
|
||||
|
||||
if (index > -1) {
|
||||
listeners.splice(index, 1);
|
||||
this.listeners.set(label, listeners);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
emit(label, ...args) {
|
||||
let listeners = this.listeners.get(label);
|
||||
|
||||
if (listeners && listeners.length) {
|
||||
listeners.forEach((listener) => {
|
||||
listener.callback.call(listener.vm,...args)
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
52
src/Main.js
Executable file
52
src/Main.js
Executable file
|
@ -0,0 +1,52 @@
|
|||
import Observer from './Observer'
|
||||
import Emitter from './Emitter'
|
||||
|
||||
export default {
|
||||
|
||||
install(Vue, connection, store){
|
||||
|
||||
if(!connection) throw new Error("[Vue-Socket.io] cannot locate connection")
|
||||
|
||||
let observer = new Observer(connection, store)
|
||||
|
||||
Vue.prototype.$socket = observer.Socket;
|
||||
|
||||
Vue.mixin({
|
||||
beforeCreate(){
|
||||
let sockets = this.$options['sockets']
|
||||
|
||||
this.$options.sockets = new Proxy({}, {
|
||||
set: (target, key, value) => {
|
||||
Emitter.addListener(key, value, this)
|
||||
target[key] = value
|
||||
return true;
|
||||
},
|
||||
deleteProperty: (target, key) => {
|
||||
Emitter.removeListener(key, this.$options.sockets[key], this)
|
||||
delete target.key;
|
||||
return true
|
||||
}
|
||||
})
|
||||
|
||||
if(sockets){
|
||||
Object.keys(sockets).forEach((key) => {
|
||||
this.$options.sockets[key] = sockets[key];
|
||||
});
|
||||
}
|
||||
},
|
||||
beforeDestroy(){
|
||||
let sockets = this.$options['sockets']
|
||||
|
||||
if(sockets){
|
||||
Object.keys(sockets).forEach((key) => {
|
||||
delete this.$options.sockets[key]
|
||||
});
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
51
src/Observer.js
Executable file
51
src/Observer.js
Executable file
|
@ -0,0 +1,51 @@
|
|||
import Emitter from './Emitter'
|
||||
import Socket from 'socket.io-client'
|
||||
|
||||
export default class{
|
||||
|
||||
constructor(connection, store) {
|
||||
|
||||
if(typeof connection == 'string'){
|
||||
this.Socket = Socket(connection);
|
||||
}else{
|
||||
this.Socket = connection
|
||||
}
|
||||
|
||||
if(store) this.store = store;
|
||||
|
||||
this.onEvent()
|
||||
|
||||
}
|
||||
|
||||
onEvent(){
|
||||
this.Socket.onevent = (packet) => {
|
||||
Emitter.emit(packet.data[0], packet.data[1]);
|
||||
|
||||
if(this.store) 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)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
commitStore(type, payload){
|
||||
|
||||
if(type.split('_')[0].toUpperCase() === 'SOCKET'){
|
||||
|
||||
if(this.store._mutations[type])
|
||||
this.store.commit(type, payload)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
136
src/emitter.js
136
src/emitter.js
|
@ -1,136 +0,0 @@
|
|||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}`);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
75
src/index.js
75
src/index.js
|
@ -1,75 +0,0 @@
|
|||
import Mixin from './mixin';
|
||||
import Logger from './logger';
|
||||
import Listener from './listener';
|
||||
import Emitter from './emitter';
|
||||
import SocketIO from 'socket.io-client';
|
||||
|
||||
export default class VueSocketIO {
|
||||
|
||||
/**
|
||||
* lets take all resource
|
||||
* @param io
|
||||
* @param vuex
|
||||
* @param debug
|
||||
* @param options
|
||||
*/
|
||||
constructor({connection, vuex, debug, options}){
|
||||
|
||||
Logger.debug = debug;
|
||||
this.io = this.connect(connection, options);
|
||||
this.emitter = new Emitter(vuex);
|
||||
this.listener = new Listener(this.io, this.emitter);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Vue.js entry point
|
||||
* @param Vue
|
||||
*/
|
||||
install(Vue){
|
||||
|
||||
const version = Number(Vue.version.split('.')[0])
|
||||
|
||||
if (version >= 3) {
|
||||
Vue.config.globalProperties.$socket = this.io;
|
||||
Vue.config.globalProperties.$vueSocketIo = this;
|
||||
} else {
|
||||
Vue.prototype.$socket = this.io;
|
||||
Vue.prototype.$vueSocketIo = this;
|
||||
}
|
||||
|
||||
Vue.mixin(Mixin);
|
||||
|
||||
Logger.info('Vue-Socket.io plugin enabled');
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* registering SocketIO instance
|
||||
* @param connection
|
||||
* @param options
|
||||
*/
|
||||
connect(connection, options){
|
||||
|
||||
if(connection && typeof connection === 'object'){
|
||||
|
||||
Logger.info('Received socket.io-client instance');
|
||||
|
||||
return connection;
|
||||
|
||||
} else if(typeof connection === 'string'){
|
||||
|
||||
Logger.info('Received connection string');
|
||||
|
||||
return this.io = SocketIO(connection, options);
|
||||
|
||||
} else {
|
||||
|
||||
throw new Error('Unsupported connection type');
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -1,51 +0,0 @@
|
|||
|
||||
export default class VueSocketIOListener {
|
||||
|
||||
/**
|
||||
* socket.io-client reserved event keywords
|
||||
* @type {string[]}
|
||||
*/
|
||||
static staticEvents = [
|
||||
'connect',
|
||||
'error',
|
||||
'disconnect',
|
||||
'reconnect',
|
||||
'reconnect_attempt',
|
||||
'reconnecting',
|
||||
'reconnect_error',
|
||||
'reconnect_failed',
|
||||
'connect_error',
|
||||
'connect_timeout',
|
||||
'connecting',
|
||||
'ping',
|
||||
'pong'
|
||||
];
|
||||
|
||||
constructor(io, emitter){
|
||||
this.io = io;
|
||||
this.register();
|
||||
this.emitter = emitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Listening all socket.io events
|
||||
*/
|
||||
register(){
|
||||
this.io.onevent = (packet) => {
|
||||
let [event, ...args] = packet.data;
|
||||
|
||||
if(args.length === 1) args = args[0];
|
||||
|
||||
this.onEvent(event, args)
|
||||
};
|
||||
VueSocketIOListener.staticEvents.forEach(event => this.io.on(event, args => this.onEvent(event, args)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcast all events to vuejs environment
|
||||
*/
|
||||
onEvent(event, args){
|
||||
this.emitter.emit(event, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,35 +0,0 @@
|
|||
/**
|
||||
* shitty logger class
|
||||
*/
|
||||
export default new class VueSocketIOLogger {
|
||||
|
||||
constructor() {
|
||||
this.debug = false;
|
||||
this.prefix = '%cVue-Socket.io: ';
|
||||
}
|
||||
|
||||
info(text, data = '') {
|
||||
|
||||
if(this.debug) window.console.info(this.prefix+`%c${text}`, 'color: blue; font-weight: 600', 'color: #333333', data);
|
||||
|
||||
}
|
||||
|
||||
error() {
|
||||
|
||||
if(this.debug) window.console.error(this.prefix, ...arguments);
|
||||
|
||||
}
|
||||
|
||||
warn() {
|
||||
|
||||
if(this.debug) window.console.warn(this.prefix, ...arguments);
|
||||
|
||||
}
|
||||
|
||||
event(text, data = ''){
|
||||
|
||||
if(this.debug) window.console.info(this.prefix+`%c${text}`, 'color: blue; font-weight: 600', 'color: #333333', data);
|
||||
|
||||
}
|
||||
|
||||
}
|
56
src/mixin.js
56
src/mixin.js
|
@ -1,56 +0,0 @@
|
|||
export default {
|
||||
|
||||
/**
|
||||
* Assign runtime callbacks
|
||||
*/
|
||||
beforeCreate(){
|
||||
|
||||
if(!this.sockets) this.sockets = {};
|
||||
|
||||
this.sockets.subscribe = (event, callback) => {
|
||||
this.$vueSocketIo.emitter.addListener(event, callback, this);
|
||||
};
|
||||
|
||||
this.sockets.unsubscribe = (event) => {
|
||||
this.$vueSocketIo.emitter.removeListener(event, this);
|
||||
};
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Register all socket events
|
||||
*/
|
||||
mounted(){
|
||||
|
||||
if(this.$options.sockets){
|
||||
|
||||
Object.keys(this.$options.sockets).forEach(event => {
|
||||
|
||||
if(event !== 'subscribe' && event !== 'unsubscribe') {
|
||||
this.$vueSocketIo.emitter.addListener(event, this.$options.sockets[event], this);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* unsubscribe when component unmounting
|
||||
*/
|
||||
beforeDestroy(){
|
||||
|
||||
if(this.$options.sockets){
|
||||
|
||||
Object.keys(this.$options.sockets).forEach(event => {
|
||||
|
||||
this.$vueSocketIo.emitter.removeListener(event, this);
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
37
webpack.config.js
Normal file → Executable file
37
webpack.config.js
Normal file → Executable file
|
@ -1,28 +1,31 @@
|
|||
var path = require('path');
|
||||
var webpack = require('webpack');
|
||||
module.exports = {
|
||||
mode: process.env.NODE_ENV,
|
||||
entry: ["./src/index.js"],
|
||||
entry: ['./src/Main.js'],
|
||||
output: {
|
||||
library: "VueSocketIO",
|
||||
libraryTarget: "umd",
|
||||
libraryExport: "default",
|
||||
filename: "vue-socketio.js",
|
||||
globalObject: "typeof self !== 'undefined' ? self : this"
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
filename: 'build.js',
|
||||
library: ['VueSocketio'],
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
devtool: "source-map",
|
||||
plugins: [
|
||||
new webpack.optimize.UglifyJsPlugin({
|
||||
compress: {
|
||||
warnings: false
|
||||
}
|
||||
})
|
||||
],
|
||||
module: {
|
||||
rules: [
|
||||
loaders: [
|
||||
{
|
||||
test: /\.js$/,
|
||||
exclude: /node_modules/,
|
||||
use: {
|
||||
loader: "babel-loader",
|
||||
options: {
|
||||
plugins: [
|
||||
"@babel/plugin-proposal-class-properties",
|
||||
"@babel/plugin-transform-classes"
|
||||
]
|
||||
}
|
||||
loader: 'babel-loader',
|
||||
query: {
|
||||
presets: ['es2015']
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
Loading…
Add table
Reference in a new issue