Pusher:在TestChannel上没有App \ Events \ Event

时间:2018-07-12 10:35:52

标签: javascript php laravel pusher

我建立了Laravel广播,计划将其实现为实时聊天应用。在客户端页面上检查时,控制台日志显示:

  

推杆:事件记录:   {"event":"App\\Events\\Event","data":{"message":"Greetings from PrinceLuo!"},"channel":"testChannel"}

     

推杆:testChannel上没有App \ Events \ Event的回调

它只是忽略确实存在的回调函数……

顺便说一句,我还没有安装npm,所以我使用的是Pusher仪表板建议的简单Javascript代码,而不是Laravel建议的Vue代码。

在控制台日志和Pusher仪表板上,我都可以看到服务器发送的广播消息。

这是我的客户端代码:

<!DOCTYPE html>
<html>
    <!DOCTYPE html>
<head>
  <title>Pusher Test</title>

  <script src="{{ asset('js/pusher.min.js') }}"></script>
  <script>

    // Enable pusher logging - don't include this in production
    Pusher.logToConsole = true;

    var pusher = new Pusher('****************', {
      cluster: 'ap1',
      encrypted: true
    });

    var channel = pusher.subscribe('testChannel');
    channel.bind('App\Events\Event', function(data) {
  console.log(data);
});


  </script>
</head>
<body>
  <h1>Pusher Test</h1>
  <p>
    Try publishing an event to channel <code>testChannel</code>
    with event name <code>Event</code>.
  </p>
</body>
</html>

只需隐藏按键即可~~

我已经搜索了一些类似的案例。但是没有人能给我答案。 有人遇到过这个案件或对此有任何想法吗?


更新:

我还为需要的任何人在这里发布了服务器端代码:

<?php

namespace App\Events;

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

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

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

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
//        return new PrivateChannel('channel-name');
//        return new PrivateChannel('testChannel');
        return new \Illuminate\Broadcasting\Channel('testChannel');
    }
}

这是我的路线:

Route::get('test_event',function(){
    event(new Event('Greetings from PrinceLuo!'));
});

Route::get('test_listen',function(){
    return view('listenBroadcast');
});

2 个答案:

答案 0 :(得分:1)

对于那些对此案感兴趣的人,我将发布为解决该问题所做的事情:

请注意,推送记录器显示【App \ Events \ Event】可以逃避反斜杠的功能。因此,在JavaScript中,我们必须对其进行相同的更改:

channel.bind('App\\Events\\Event', function(data){});

简单但必不可少。

答案 1 :(得分:0)

这就是我所做的

channel.bind('pusher:subscription_succeeded', function(members) {
    // alert('successfully subscribed!');
 });

 channel.bind("App\\Events\\NewComment", function(data) {
     console.log(data);
 });