Skip to content

Instantly share code, notes, and snippets.

@hkan
Last active May 18, 2016 09:33
Show Gist options
  • Save hkan/5bec4aaece19396d2cbe2e55710ae7f0 to your computer and use it in GitHub Desktop.
Save hkan/5bec4aaece19396d2cbe2e55710ae7f0 to your computer and use it in GitHub Desktop.
[Socket.io] Define events and connect later at will
import SomeComponent from './SomeComponent.vue'
new Vue({
data: {
/*
* This makes sure that a socket instance will be available to add
* event listeners before any actual connection to socket server has
* been established.
*
* `autoConnect: false` means that the socket instance will be created,
* but it will not try to connect until `socket.connect()` is called.
*/
socket: io('', { autoConnect: false })
},
components: {
'some-component': SomeComponent
},
methods: {
connectToSocket(options) {
this.socket.io.uri = options.uri + '?token=' + options.token
this.socket.connect()
},
authAndStuff() {
/*
* Send a request to your back-end application and it shall
* return successfuly with user information and a socket URI
* if user is logged in; or return with a 403 status code so
* you can redirect to login page or open a login modal.
*/
yourAuthorizationQuery()
.then(response => {
// Current logged in user's info
this.user = response.data.user
// Connect to socket with given socket info
this.connectToSocket(response.data.socket)
})
.catch(response => {
// You ain't logged in bruh
})
}
},
ready() {
// Start the process once the component is compiled and ready
this.authAndStuff()
}
})
{
"user": {
"id": 1234,
"name": "John Doe"
},
"socket": {
"uri": "https://example.com:3000",
"token": "JWT token generated at back-end. This is for authentication security. It is optional."
}
}
<template>
<div class="some-class">
{{ someVariable }}
</div>
</template>
<script>
export default {
data() {
return {
someVariable: 'content'
}
},
ready() {
// This won't fail because the socket instance is already created
this.$root.socket.on('new-message', data => {
// do stuff
})
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment