在 Laravel 中使用推送器收听消息
listen to messages using pusher in Laravel
当我设置了按摩后,我需要在日志中收到回声消息我可以通过此代码收听发送给我的消息吗
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script type="text/javascript">
// Enable pusher logging - don't include this in production
Pusher.logToConsole = false;
var pusher = new Pusher('34b9ea6826c359c41c3f', {
cluster: 'eu',
encrypted: true
});
var channel = pusher.subscribe('Messages');
channel.bind('msgSend{{$id}}msgReceive{{Auth::user()->id}}', function(data) {
$('.adsx').append(data.html);
$("html,body").animate({scrollTop: $('.adsx')[0].scrollHeight}, 0);
});
我认为你需要通过 artisan php artisan make:event addANameHere
创建一个 Laravel Event
之后,在 事件中 您需要添加一个要播放的频道
例如
class addANameHere implements ShouldBroadcast {
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user_id;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($user_id)
{
$this->user_id = $user_id;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return ['alert-user-'.$this->user_id];
}
然后,您可以收到这样的消息:
var pusher = new Pusher("34b9ea6826c359c41c3f", {
cluster: 'eu',
encrypted: false,
});
var channel = pusher.subscribe('alert-user-{{ Auth::user()->id }}');
channel.bind('App\Events\addANameHere', function(data) {
// Do whatever you want here ...
});
为了触发该事件(发送消息时),您可以这样调用事件 Class:
\Event::dispatch(new addANameHere($user_id));
$user_id
是您希望看到该消息的用户。
我希望我帮到了..
当我设置了按摩后,我需要在日志中收到回声消息我可以通过此代码收听发送给我的消息吗
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script type="text/javascript">
// Enable pusher logging - don't include this in production
Pusher.logToConsole = false;
var pusher = new Pusher('34b9ea6826c359c41c3f', {
cluster: 'eu',
encrypted: true
});
var channel = pusher.subscribe('Messages');
channel.bind('msgSend{{$id}}msgReceive{{Auth::user()->id}}', function(data) {
$('.adsx').append(data.html);
$("html,body").animate({scrollTop: $('.adsx')[0].scrollHeight}, 0);
});
我认为你需要通过 artisan php artisan make:event addANameHere
之后,在 事件中 您需要添加一个要播放的频道 例如
class addANameHere implements ShouldBroadcast {
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user_id;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($user_id)
{
$this->user_id = $user_id;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return ['alert-user-'.$this->user_id];
}
然后,您可以收到这样的消息:
var pusher = new Pusher("34b9ea6826c359c41c3f", {
cluster: 'eu',
encrypted: false,
});
var channel = pusher.subscribe('alert-user-{{ Auth::user()->id }}');
channel.bind('App\Events\addANameHere', function(data) {
// Do whatever you want here ...
});
为了触发该事件(发送消息时),您可以这样调用事件 Class:
\Event::dispatch(new addANameHere($user_id));
$user_id
是您希望看到该消息的用户。
我希望我帮到了..