client.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. var VueRemote = {}
  2. VueRemote.install = function (Vue, options) {
  3. Vue.Remote = (function (options) {
  4. var Client = null,
  5. Handlers = Object.create(null),
  6. socketPump = [],
  7. pumpInterval = null
  8. var options = options || {}
  9. options.secure = options.secure || false
  10. options.host = options.host || "localhost"
  11. options.port = options.port || 8080
  12. options.identifier = options.identifier || 'event'
  13. options.endpoint = options.endpoint || ''
  14. options.camelCase = options.camelCase || false
  15. /**
  16. * Connect to Websocket Server
  17. */
  18. function connect() {
  19. Client = new WebSocket('ws://' + options.host + (options.port ? ':' + options.port : ''))
  20. //Client = new WebSocket(`${(options.secure ? 'wss://' : 'ws://')}${options.host}${options.port ? ':' + options.port : ''}/${options.endpoint}`, options.protocol)
  21. Client.onopen = openHandler
  22. Client.onerror = errorHandler
  23. Client.onmessage = messageHandler
  24. Client.onclose = closeHandler
  25. }
  26. /**
  27. * Handle Server Connection Event
  28. *
  29. * @param {Event} open
  30. */
  31. function openHandler(open) {
  32. console.log("Connected to Web Server")
  33. console.log(open)
  34. if (options.openHandler) options.openHandler(open)
  35. }
  36. /**
  37. * Handle Server Errors
  38. *
  39. * @param {Event} error
  40. */
  41. function errorHandler(error) {
  42. console.log("Error occured")
  43. console.log(error)
  44. if (options.errorHandler) options.errorHandler(error)
  45. }
  46. /**
  47. * Handle Messages Returned from the Server
  48. *
  49. * @param {MessageEvent} message
  50. * @returns
  51. */
  52. function messageHandler(message) {
  53. var Json = JSON.parse(message.data)
  54. var identifier = Json[options.identifier]
  55. var Events = Handlers[identifier]
  56. if (Events) {
  57. Events.forEach(
  58. function (Event) {
  59. //Event.callback.apply(Event.thisArg, [Json.data])
  60. //Adapt to all respone format
  61. Event.callback.apply(Event.thisArg, [Json])
  62. }
  63. )
  64. }
  65. }
  66. /**
  67. * {EventListener} For When the Websocket Client Closes the Connection
  68. *
  69. * @param {CloseEvent} close
  70. */
  71. function closeHandler(close) {
  72. if (options.closeHandler) options.closeHandler(close)
  73. if (pumpInterval) {
  74. window.clearInterval(pumpInterval)
  75. pumpInterval = null
  76. }
  77. Client = null
  78. }
  79. /**
  80. * Attaches Handlers to the Event Pump System
  81. *
  82. * @param {Boolean} server True/False whether the Server should process the trigger
  83. * @param {String} identifier Unique Name of the trigger
  84. * @param {Function} callback Function to be called when the trigger is tripped
  85. * @param {Object} [thisArg] Arguement to be passed to the handler as `this`
  86. */
  87. function attachHandler(identifier, callback, thisArg) {
  88. console.log('Attach '+identifier)
  89. !(Handlers[identifier] || (Handlers[identifier] = [])).push({
  90. callback: callback,
  91. thisArg: thisArg
  92. })
  93. }
  94. /**
  95. * Detaches Handlers from the Event Pump System
  96. *
  97. * @param {String} identifier Unique Name of the trigger
  98. * @param {Function} callback Function to be called when the trigger is tripped
  99. */
  100. function detachHandler(identifier, callback) {
  101. if (arguments.length === 0) {
  102. Handlers = Object.create(null)
  103. return
  104. }
  105. var Handler = Handlers[identifier]
  106. if (!Handler) return
  107. if (arguments.length === 1) {
  108. Handlers[identifier] = null
  109. return
  110. }
  111. for (var index = Handler.length - 1; index >= 0; index--) {
  112. if (Handler[index].callback === callback || Handler[index].callback.fn === callback) {
  113. Handler.splice(index, 1)
  114. }
  115. }
  116. }
  117. /**
  118. * Handles Event Triggers
  119. *
  120. * @param {String} identifier
  121. * @returns
  122. */
  123. function emitHandler(identifier) {
  124. var varargs = arguments[1] || undefined,
  125. args = []
  126. if (arguments.length > 2) {
  127. args = arguments.length > 1 ? [].slice.apply(arguments, [1]) : []
  128. }
  129. if (args.length > 1) {
  130. socketPump.push(
  131. JSON.stringify({
  132. 'event': identifier,
  133. 'data': args
  134. })
  135. )
  136. return
  137. }
  138. socketPump.push(
  139. JSON.stringify({
  140. 'event': identifier,
  141. 'data': varargs
  142. })
  143. )
  144. }
  145. /**
  146. * Sends Messages to the Websocket Server every 250 ms
  147. *
  148. * @returns
  149. */
  150. function pumpHandler() {
  151. if (socketPump.length === 0) return
  152. if (!Client) connect()
  153. if (Client.readyState === WebSocket.OPEN) {
  154. socketPump.forEach(
  155. function (item) { Client.send(item) }
  156. )
  157. socketPump.length = 0
  158. }
  159. }
  160. if (!pumpInterval) window.setInterval(pumpHandler, 250)
  161. connect();
  162. return {
  163. connect: connect,
  164. disconnect: function () {
  165. if (Client) {
  166. Client.close()
  167. Client = null
  168. }
  169. },
  170. attach: attachHandler,
  171. detach: detachHandler,
  172. emit: emitHandler
  173. }
  174. })(options)
  175. Vue.mixin({
  176. created: function () {
  177. if (this.$options.remote) {
  178. Handlers = this.$options.remote
  179. for (var name in Handlers) {
  180. if (Handlers.hasOwnProperty(name) && typeof Handlers[name] === "function") {
  181. Vue.Remote.attach(name, Handlers[name], this)
  182. }
  183. }
  184. }
  185. },
  186. beforeDestroy: function () {
  187. if (this.$options.remote) {
  188. Handlers = this.$options.remote
  189. for (var name in Handlers) {
  190. if (Handlers.hasOwnProperty(name) && typeof Handlers[name] === "function") {
  191. Vue.Remote.detach(name, Handlers[name])
  192. }
  193. }
  194. }
  195. }
  196. });
  197. Vue.prototype.$remote = {
  198. $on: function (identifier, callback) {
  199. Vue.Remote.attach(identifier, callback, this)
  200. return this
  201. },
  202. $once: function (identifier, callback) {
  203. var thisArg = this
  204. function once() {
  205. Vue.remote.detach(identifier, callback)
  206. callback.apply(thisArg, arguments)
  207. }
  208. once.fn = callback
  209. Vue.Remote.attach(identifier, once, thisArg)
  210. return thisArg
  211. },
  212. $off: function (identifier, callback) {
  213. Vue.Remote.detach(identifier, callback, this)
  214. return this
  215. },
  216. $emit: Vue.Remote.emit
  217. };
  218. };