This repository has been archived by the owner on Oct 29, 2024. It is now read-only.
forked from happyDemon/vue-echo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
vue-echo.js
87 lines (75 loc) · 2.97 KB
/
vue-echo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import Echo from 'laravel-echo';
export default {
install(Vue, options) {
if (!options) {
throw new Error("[Vue-Echo] cannot locate options");
}
if (typeof options !== 'object') {
throw new Error("[Vue-Echo] cannot initiate options");
}
if(typeof options.socketId == 'function')
{
Vue.prototype.$echo = options;
}
else
{
Vue.prototype.$echo = new Echo(options);
}
Vue.mixin({
mounted() {
let channel = this.$options['channel'];
const events = this.$options['echo'];
// Exit function if channel is undefined or null.
if(channel == undefined)
{
return
}
// if channel is a function, evaluate the channel by running the provided callback function.
if(typeof channel === 'function')
{
channel = channel(this)
}
// After we evaluated potential callback, break if provided channel is not a string
if(typeof channel !== 'string')
{
throw new Error("[Vue-Echo] channel needs to be of type string");
}
// Join correct channel
if(channel.startsWith('private:'))
{
this.channel = this.$echo.private(channel.replace('private:', ''))
}
else if(channel.startsWith('presence:'))
{
this.channel = this.$echo.join(channel.replace('presence:', ''))
}
else
{
this.channel = this.$echo.channel(channel);
}
// Add user-provided event listeners for the socket
if(events)
{
Object.keys(events).forEach(key => {
// Bind the VM as second parameter
this.channel.listen(key, (payload) => events[key](payload, this));
}, this);
}
/* Cleanup: Leave the channel on destroyed vue instance.
* - Use an programmatic listener instead of the normal "beforeDestroy". This way, we do not have to do validation of the variable "channel" twice.
*/
this.$once('hook:beforeDestroy', () => {
if(channel.startsWith('private:'))
{
channel = channel.replace('private:', '');
}
else if(channel.startsWith('presence:'))
{
channel = channel.replace('presence:', '');
}
this.$echo.leave(channel);
})
}
})
}
}