@nioterzor

В laravel echo по непонятной причине не срабатывает обработчик события?

Есть событие

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class FieldWasUpdated implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;
    public $instance;
    public $key;
    public $value;

/**
 * Create a new event instance.
 *
 * @return void
 */
public function __construct($instance, $key, $value)
{
    $this->instance = $instance;
    $this->key = $key;
    $this->value = $value;
}

/**
 * Get the channels the event should broadcast on.
 *
 * @return Channel|array
 */
public function broadcastOn()
{
    return new Channel("model." . $this->instance->getModelType() . "." . $this->instance->id);
}


    //public function broadcastAs() {
    //    return "FieldWasUpdated"; commented out for testing
    //}
}


Код на клиенте

window.Echo = new window.LaravelEcho({
            broadcaster: 'socket.io',
            host: window.location.hostname + ':3000'
        });
        // I use different types of `listen` for testing
        Echo.channel("model.ANNOUNCEMENT.2")
            .listen(".*", function(e) {
                console.log(e);
            })
            .listen("*", function(e) {
                console.log(e);
            })
            .listen("FieldWasUpdated", function(e) {
                console.log(e);
            })
            .listen(".FieldWasUpdated", function(e) {
                console.log(e);
            })


Код сервера node
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();


http.listen(3000, function(){
console.log('Listening on Port 3000');
});

redis.psubscribe('*', function(err, count) {
console.log(err, count);
});
redis.on('pmessage', function(subscribed, channel, message) {
    // different types of emit for testing
    message = JSON.parse(message);
    const ev = channel + ":" + message.event;
    io.emit(ev, message.data);
    io.emit(channel, message);
    io.emit(message, channel);
    io.emit(channel, message.event, message.data);
    io.emit(channel, message);
    io.emit(channel, message.data, message.event);
});


В хроме при срабатывании события видно, что io.emit сработали все
https://i.stack.imgur.com/gYIHR.png

Когда раскомментирую функцию broadcastAs - ничего не меняется.
Переименовываю channel - ничего не меняется.
В интернете много примеров, когда у людей не заводится с полпинка laravel-echo, но здесь проблема в том, что события доходят до браузера, а обработчики не вызываются. Много различных io.emit и listen потому, что ни один все равно не срабатывает)

Где я ошибаюсь?
  • Вопрос задан
  • 880 просмотров
Решения вопроса 1
@nioterzor Автор вопроса
Решение на сервере
redis.psubscribe('*', function(err, count) {
    console.log(err, count);
});
redis.on('pmessage', function(subscribed, channel, message) {
    message = JSON.parse(message);
    io.emit(message.event, channel, message.data);
});


На клиенте
Echo.channel("test-channel")
            .listen("FieldWasUpdated", function(e) {
                console.log(e);
            })
            .listen(".App.Events.FieldWasUpdated", function(e) {
                console.log(e);
            })
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
КРАФТТЕК Санкт-Петербург
от 60 000 до 80 000 ₽
Brightdata Тель-Авив
от 5 500 до 6 500 $
Rocket Брянск
от 60 000 до 100 000 ₽
28 мая 2024, в 08:33
500000 руб./за проект
28 мая 2024, в 07:56
1500 руб./в час
28 мая 2024, в 06:55
400 руб./в час