From f01fdebdd1f5673abc0f0afe9da2c4877d7b4df8 Mon Sep 17 00:00:00 2001 From: Metin Seylan Date: Sun, 8 May 2016 23:41:03 +0300 Subject: [PATCH] not finish yet testing --- package.json | 5 ++- vue-socketio.js | 84 +++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 85 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index a84bc2b..dadd23a 100644 --- a/package.json +++ b/package.json @@ -22,5 +22,8 @@ "bugs": { "url": "https://github.com/MetinSeylan/Vue-Socket.io/issues" }, - "homepage": "https://github.com/MetinSeylan/Vue-Socket.io#readme" + "homepage": "https://github.com/MetinSeylan/Vue-Socket.io#readme", + "dependencies": { + "socket.io-client": "^1.4.6" + } } diff --git a/vue-socketio.js b/vue-socketio.js index 8d8f492..11942b6 100644 --- a/vue-socketio.js +++ b/vue-socketio.js @@ -1,3 +1,81 @@ -/** - * Created by Metin on 6.5.2016. - */ +;(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") + } + + var socket = Socketio(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 me = this; + if (this.$options.hasOwnProperty("sockets")) { + socket.on("*", function (emit, data) { + if (me.$options.sockets.hasOwnProperty(emit)) { + me.$options.sockets[emit](data); + } + }); + + methods.forEach(function (m) { + socket.on(m, function (data) { + if (me.$options.sockets.hasOwnProperty(m)) { + me.$options.sockets[m](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; + } + + +})(); \ No newline at end of file