C
C
Corsair_TM2019-11-14 01:23:49
Socket.io
Corsair_TM, 2019-11-14 01:23:49

How to listen to 2 events on the same channel?

Goodnight! There is a chat in which receiving messages and a list of online users is performed via Socket.io.
Event code:

class ChatOnline implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $data;

    public function __construct($data)
    {
        $this->data = $data;
        $this->dontBroadcastToCurrentUser();
    }

    public function broadcastOn()
    {
        return new PresenceChannel('chat');
    }
}

The JS code where the connection to the channel is performed:
Echo.join('chat')
        .here((users) => {
            $.each(users, function(index, value){
                $('#chat-online').append('<div id="user-' + value.id + '">' + value.name + '</div>');
            });
        })
        .joining((user) => {
            $('#chat-online').append('<div id="user-' + user.id + '">' + user.name + '</div>');
        })
        .leaving((user) => {
            $('#user-' + user.id).remove();
        }).listen('ChatOnline', (data) => {
            switch (data.data.type) {
                case 1: Выполняется если приходит сообщение; break;
                case 2: Выполняется если было удалено сообщение; break;
        });

When sending a message, I pass the parameter type = 1 to data, when deleting a message, type = 2. Something tells me that this method is dirty, tell me how to do it right, send two events to 1 channel or something else?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Wells, 2019-11-14
@Corsair_TM

One event equals one action.
type in this case is shit code, since there is no reason to use it, rather than separate events (which are easier to maintain, which can be typed without pain, etc.).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question