Compare commits

..

No commits in common. "master" and "1.0.2" have entirely different histories.

22 changed files with 481 additions and 820 deletions

23
.gitignore vendored
View file

@ -1,23 +0,0 @@
.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

View file

@ -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/

View file

@ -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.

225
README.md
View file

@ -1,192 +1,59 @@
<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
socket.io implemantation for vuejs
note: this repo for vuejs 1, vuejs 2 soon
<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>
## Install
###### 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>
``` bash
npm install vue-socket.io --save
```
or
#### 🚀 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'
``` bash
bower install vue-socket.io
```
## Usage
Vue.use(new VueSocketIO({
debug: true,
connection: 'http://metinseylan.com:1992',
vuex: {
store,
actionPrefix: 'SOCKET_',
mutationPrefix: 'SOCKET_'
``` js
import VueSocketio from 'vue-socket.io'; // for ES6
// var VueSocketio = require('vue-socket.io') // for commonjs
Vue.use(VueSocketio, 'http://socketserver.com:1923'); // Automaticly socket connect from url string
/*
import socketio from 'socket.io-client';
var ioInstance = socketio('http://socketserver.com:1923');
Vue.use(VueSocketio, ioInstance); // bind custom socketio instance
*/
var vm = new Vue({
sockets:{
connect: function(){
console.log('socket connected')
},
options: { path: "/my-app/" } //Optional options
}))
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
```
##### 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')
```
**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
#### 🌈 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)')
}
},
methods: {
clickButton: function (data) {
// $socket is socket.io-client instance
this.$socket.emit('emit_method', data)
}
}
})
```
##### 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.
]
customEmit: function(){
console.log('this method fired by socket server. eg: io.emit("customEmit", data)')
}
},
mounted () {
this.$socket.subscribe("kebab-case", function(data) {
console.log("This event was fired by eg. sio.emit('kebab-case')", data)
})
methods: {
clickButton: function(val){
// $socket is socket.io-client instance
this.$socket.emit('emit_method', val);
}
}
}
```
#### 🏆 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
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {},
mutations: {
"<MUTATION_PREFIX><EVENT_NAME>"() {
// do something
}
},
actions: {
"<ACTION_PREFIX><EVENT_NAME>"() {
// do something
}
}
})
```
## Stargazers over time
## Example
[Realtime Car Tracker System](http://metinseylan.com/)
[![Stargazers over time](https://starcharts.herokuapp.com/MetinSeylan/Vue-Socket.io.svg)](https://starcharts.herokuapp.com/MetinSeylan/Vue-Socket.io)
[Simple Chat App](http://metinseylan.com/vuesocketio/)
<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>
## License
[WTFPL](http://www.wtfpl.net/)

24
bower.json Normal file
View file

@ -0,0 +1,24 @@
{
"name": "vue-socket.io",
"description": "Socket.io implemantation for VueJs",
"main": "vue-socketio.js",
"authors": [
"Metin Seylan"
],
"license": "MIT",
"keywords": [
"vuejs",
"socket",
"vue",
"socket",
"socket.io"
],
"homepage": "https://github.com/MetinSeylan/Vue-Socket.io",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}

12
dist/vue-socketio.js vendored

File diff suppressed because one or more lines are too long

View file

@ -1,114 +0,0 @@
# Vue-Socket.io
[![NPM version](https://img.shields.io/npm/v/vue-socket.io.svg)](https://www.npmjs.com/package/vue-socket.io)
![VueJS v2 compatible](https://img.shields.io/badge/Vuejs%202-compatible-green.svg)
<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/)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

70
example/index.html Normal file
View file

@ -0,0 +1,70 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vue-Socket.io</title>
<!-- Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="text-center">Vue-Socket.io</h1>
<div class="container">
<div v-if="!join" id="join" class="text-center">
<form @submit.prevent="joinChat(name)">
<div class="form-group">
<input type="text" max="12" class="form-control input-lg text-center" v-model="name" placeholder="Name">
</div>
<button class="btn btn-primary btn-lg" type="submit">Join Chat</button>
<br>
<a href="https://github.com/metinseylan/vue-socket.io">Github</a>
</form>
</div>
<div v-if="join" id="group">
<div class="users">
<h4>Users</h4>
<ul class="list-unstyled">
<li v-for="user in users" track-by="$index">{{user}}</li>
</ul>
</div>
<div class="chat">
<div class="messages">
<ul class="list-unstyled">
<li v-for="m in messages" :class="{me: (m.name === name), clearfix: true}">
<div class="name">{{m.name}}</div>
<span>{{m.message}}</span>
</li>
</ul>
</div>
<div class="input">
<form @submit.prevent="send(message)">
<div class="input-group">
<input type="text" class="form-control" v-model="message" placeholder="uyudun mu?...">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">-></button>
</span>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.22/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.min.js"></script>
<script src="../vue-socketio.min.js"></script>
<script src="script.js"></script>
</body>
</html>

49
example/script.js Normal file
View file

@ -0,0 +1,49 @@
Vue.use(VueSocketio, 'http://metinseylan.com:1923');
new Vue({
el: '.container',
data: {
join: false,
name: null,
users: null,
message: null,
messages: {}
},
methods: {
joinChat: function (name) {
if (name) {
this.$socket.emit('join', name);
}
},
send: function (message) {
if (message) {
this.$socket.emit('send', message);
this.$set('message', null);
}
}
},
watch: {
messages: function () {
setTimeout(function () {
$('.messages ul').scrollTop(999999999);
}, 100)
}
},
sockets: {
users: function (users) {
this.$set('users', users);
},
joined: function () {
this.$set('join', true)
},
messages: function (data) {
this.$set('messages', data);
},
onmessage: function (data) {
this.messages.push(data);
},
adduser: function (user) {
this.users.push(user);
}
}
});

64
example/server/server.js Normal file
View file

@ -0,0 +1,64 @@
var socket = require('socket.io');
var io = socket.listen(1923);
var users = [];
var messages = [];
var names = [];
io.on('connection', function(client){
client.on('join', function(name){
client.join('chat');
users.push(name);
names[client.id] = name;
client.emit('users', users);
client.emit('messages', messages);
client.emit('joined', true);
client.broadcast.emit('adduser', name);
});
client.on('send', function(message){
var data = {
name: names[client.id],
message: message
};
if(messages.length > 10){
messages.splice(0, 10);
}
messages.push(data);
io.emit('onmessage', data);
});
client.on('disconnect', function(){
var name = names[client.id];
delete names[client.id];
var index = users.indexOf(name);
if(index!=-1){
delete users[index];
}
users = users.filter(Boolean)
io.emit('users', users);
});
});

133
example/style.css Normal file
View file

@ -0,0 +1,133 @@
body {
color: #373a3c;
background-color: #f9f9f9;
}
* {
border-radius: 0 !important;
}
.container {
max-width: 700px;
box-shadow: 0 2px 3px rgba(0, 0, 0, .05);
background-color: #fff;
border: 1px solid #eee;
padding: 15px;
}
.users {
border-right: 1px solid #eee;
float: left;
width: 140px;
}
.users ul {
height: 250px;
overflow-y: scroll;
margin: 0;
}
.users h4 {
margin: 0;
border-bottom: 1px solid #eee;
padding-bottom: 3px;
margin-bottom: 5px;
}
::-webkit-scrollbar {
width: 5px;
}
::-webkit-scrollbar-thumb {
background: #666;
}
.chat {
width: 528px;
float: left;
padding-left: 15px;
position: relative;
height: 278px;
}
.chat .messages ul {
height: 240px;
margin: 0;
overflow-y: scroll;
padding-top: 5px;
}
.chat .messages ul li .name {
font-size: 12px;
font-weight: bold;
margin-bottom: 5px;
}
.chat .messages ul li {
margin-bottom: 10px;
}
.chat .messages ul li span {
border-radius: 5px !important;
background: #E0EDFF;
padding: 5px 12px;
font-size: 15px;
}
.chat .messages ul li.me {
text-align: right;
margin-right: 10px;
}
.chat .input {
position: absolute;
bottom: 0;
}
@media screen and (max-width: 768px) {
body, html {
position: relative;
width: 100%;
height: 100%;
}
#join .btn {
display: block;
width: 100%;
}
.container {
position: absolute;
width: 100%;
height: 89%;
}
h1 {
margin: 4% 0;
}
.users {
display: none;
}
.chat {
float: none;
padding: 0;
height: 100%;
width: 100%;
position: absolute;
}
.chat .messages {
height: 90%;
}
.chat .messages ul {
height: 100%;
}
#group {
height: 100%;
position: relative;
}
}

63
index.d.ts vendored
View file

@ -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>
}

View 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": "1.0.1",
"description": "socket.io implemantation for vuejs",
"main": "vue-socketio.js",
"scripts": {
"build": "webpack --mode=production --progress --hide-modules"
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
@ -15,30 +14,16 @@
"vuejs",
"socket",
"vue",
"socket.io",
"websocket",
"socket.io-client",
"realtime",
"flux",
"vuex",
"redux"
"socket",
"socket.io"
],
"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"
},
"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"
"socket.io-client": "^1.4.6"
}
}

View file

@ -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);
}
}
}
}
}
}

View file

@ -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');
}
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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);
});
}
}
}

85
vue-socketio.js Normal file
View file

@ -0,0 +1,85 @@
;(function () {
var Socketio = typeof require === "function"
? require("socket.io-client")
: window.io;
if (!Socketio) {
throw new Error("[Vue-Socket.io] cannot locate Socket.io")
}
var VueSocketio = {
install: function (Vue, connection) {
if (!connection) {
throw new Error("[Vue-Socket.io] cannot locate connection")
}
if (typeof connection === 'string') {
var socket = Socketio(connection);
} else if (typeof connection === 'object') {
var socket = connection;
}
/*
* Wildcard support
* http://stackoverflow.com/questions/10405070/socket-io-client-respond-to-all-events-with-one-handler
*/
var onevent = socket.onevent;
socket.onevent = function (packet) {
var args = packet.data || [];
onevent.call(this, packet);
packet.data = ["*"].concat(args);
onevent.call(this, packet);
};
var methods = [
"connect",
"error",
"disconnect",
"reconnect",
"reconnect_attempt",
"reconnecting",
"reconnect_error",
"reconnect_failed"
];
Vue.mixin({
created: function () {
var self = this;
if (this.$options.hasOwnProperty("sockets")) {
socket.on("*", function (emit, data) {
if (self.$options.sockets.hasOwnProperty(emit)) {
self.$options.sockets[emit].call(self, data);
}
});
methods.forEach(function (m) {
socket.on(m, function (data) {
if (self.$options.sockets.hasOwnProperty(m)) {
self.$options.sockets[m].call(self, data);
}
});
});
}
// Global socketio instance
this.$socket = socket;
}
});
}
};
if (typeof exports == "object") {
module.exports = VueSocketio
} else if (typeof define == "function" && define.amd) {
define([], function () {
return VueSocketio
})
} else if (window.Vue) {
window.VueSocketio = VueSocketio;
}
})();

1
vue-socketio.min.js vendored Normal file
View file

@ -0,0 +1 @@
!function(){var o="function"==typeof require?require("socket.io-client"):window.io;if(!o)throw new Error("[Vue-Socket.io] cannot locate Socket.io");var n={install:function(n,t){if(!t)throw new Error("[Vue-Socket.io] cannot locate connection");if("string"==typeof t)var e=o(t);else if("object"==typeof t)var e=t;var c=e.onevent;e.onevent=function(o){var n=o.data||[];c.call(this,o),o.data=["*"].concat(n),c.call(this,o)};var i=["connect","error","disconnect","reconnect","reconnect_attempt","reconnecting","reconnect_error","reconnect_failed"];n.mixin({created:function(){var o=this;this.$options.hasOwnProperty("sockets")&&(e.on("*",function(n,t){o.$options.sockets.hasOwnProperty(n)&&o.$options.sockets[n].call(o,t)}),i.forEach(function(n){e.on(n,function(t){o.$options.sockets.hasOwnProperty(n)&&o.$options.sockets[n].call(o,t)})})),this.$socket=e}})}};"object"==typeof exports?module.exports=n:"function"==typeof define&&define.amd?define([],function(){return n}):window.Vue&&(window.VueSocketio=n)}();

View file

@ -1,28 +0,0 @@
module.exports = {
mode: process.env.NODE_ENV,
entry: ["./src/index.js"],
output: {
library: "VueSocketIO",
libraryTarget: "umd",
libraryExport: "default",
filename: "vue-socketio.js",
globalObject: "typeof self !== 'undefined' ? self : this"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
plugins: [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-classes"
]
}
}
}
]
}
};