Last active
May 18, 2016 09:33
-
-
Save hkan/5bec4aaece19396d2cbe2e55710ae7f0 to your computer and use it in GitHub Desktop.
[Socket.io] Define events and connect later at will
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
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() | |
} | |
}) |
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
<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