Laravel Echo callback
Asked Answered
B

3

8

I'm looking into Laravel Echo (With socket.io as connector)

But I can't find out how to bind a callback when user/visitor succeed or not connecting to the socket (Not channel), but generally if connected.

import Echo from "laravel-echo"; //import Laravel-echo

if(typeof(io) != 'undefined'){ //check if io loaded
    //init Echo
    window.Echo = new Echo({
        broadcaster: 'socket.io',
        host: { path: '/socket.io' }
    });
}

So here I do check if io exist, then most probably socket is up.

But can we bind a callback like we can do with socket.io: Example from socket.io docs

const socket = io('http://localhost');

console.log(socket.id); // undefined

socket.on('connect', () => {
  console.log(socket.id); // 'here we can get socket id'
});

The reason why I need a callback is to get the socket id and initiate other scripts.

Bader answered 22/9, 2017 at 8:42 Comment(0)
B
16

Looking deeper into the laravel echo source code, I've found that there is on event binder, that we can't call straight away echo.on('connect', ...). But we have access to connector and the actual socket so here is the solution:

if(typeof(io) != 'undefined'){ //check if io loaded
    //init Echo
    echo = new Echo({
        broadcaster: 'socket.io',
        host: { path: '/socket.io' }
    });

    //bind our events
    echo.connector.socket.on('connect', function(){
        console.log('connected', echo.socketId());
    });
    echo.connector.socket.on('disconnect', function(){
        console.log('disconnected');
    });
    echo.connector.socket.on('reconnecting', function(attemptNumber){
        console.log('reconnecting', attemptNumber);
    });
}
Bader answered 22/9, 2017 at 12:54 Comment(0)
S
2

For anyone trying to figure out how to return a promise from a Presence channel here connection, the following worked for me:

// return a promise and resolve when the subscription has succeeded
return new Promise((resolve, reject) => {
    echo.connector.channels['presence-' + channel].subscription.bind('pusher:subscription_succeeded', () => {
        return resolve(true);
    });
});
Sleek answered 27/3, 2019 at 12:57 Comment(0)
E
2

For those who have this requirement, there is a bind to "state_change" event. this will fire on all state changes on connection level (not channel)

echo.connector.pusher.connection.bind('state_change', function(states) {
    
    console.log(states.current)
        
})

Pusher Docs link

Elytron answered 12/7 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.