-
-
Save n3tr/b5fab439f61d8a110026f1103bb0439a to your computer and use it in GitHub Desktop.
JavaScript Singleton to connect to WebSocket (originally for React project)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// App.js | |
import { getWebSocket } from './webSocket' | |
let ws = getWebSocket() | |
ws.send(...) | |
ws.onmessage = ev => { console.log(ev.data) } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SomeComponent.js | |
import { getWebSocket } from './../webSocket' | |
let ws = getWebSocket() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Thank you Ranatchai Chernbamrung for sample socketIO singleton pattern | |
// This code is originally for my React project, but should work with any ES6 project that support `import` statement | |
// How it works | |
// 1. Create webSocket.js to establish the connection and retrieve the connection | |
// 2. In main file, import webSocket.js to establish the connection | |
// 3. In other component files, import webSocket.js to retrieve the connection | |
// webSocket.js | |
let client | |
export const getWebSocket = () => { | |
if (client) { | |
return client; | |
} | |
client = new WebSocket('ws://localhost:4237') | |
return client | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment