我正在使用laravel 5.2,并在任务完成时实现实时通知。我有一个 Activity 和一个听众。我的最终目标是当事件被推送时在页面上显示一个JavaScript警报。
App \ Events \ User \ App \ Trigger \ MarkTopicComplete.php
class MarkTopicComplete extends Event implements ShouldBroadcast{
...
public function broadcastWith(){
return [
'user_id' => $this->user_id,
'topic_id' => $this->topic_id
];
}
public function broadcastOn(){
return ['topic-complete'];
}
App \ Listeners \ User \ App \ Trigger \ MarkTopicComplete \ LogActivity
public function handle(MarkTopicComplete $event){
$this->user_id = $event->user_id;
$this->user_email = $event->user_email;
$this->topic_id = $event->topic_id;
Log::info('User '.$this->user_email.' has completed the TOPIC ID: '. $this->topic_id);
}
前端
<script src="//js.pusher.com/3.2/pusher.min.js"></script>
<script>
var pusher = new Pusher('{{ config('broadcasting.connections.pusher.key') }}', {
encrypted: true
});
Pusher.logToConsole = true;
var channel = pusher.subscribe('topic-complete');
channel.bind('App\\Events\\User\\App\\TriggerMarkTopicComplete', function(data) {
// Over here i would like to alert the frontend with the topic id that is sent from the event.
alert(data.topic_id);
});
</script>
这是我在控制台中收到的内容:
Pusher : State changed : connecting -> connected with new socket ID 204817.3725229
pusher.min.js:8 Pusher : Event sent : {"event":"pusher:subscribe","data":{"channel":"topic-complete"}}
1?session=OTk2NDUyOTMx&bundle=MQ%3D%3D&key=ODY4MTU1MjE4NWU0ZjFkYzY0YTI%3D&lib=anM%3D&version=My4yLj…:1 Uncaught TypeError: Pusher.ScriptReceivers[1] is not a function(anonymous function) @ 1?session=OTk2NDUyOTMx&bundle=MQ%3D%3D&key=ODY4MTU1MjE4NWU0ZjFkYzY0YTI%3D&lib=anM%3D&version=My4yLj…:1
pusher.min.js:8 Pusher : Event recd : {"event":"pusher_internal:subscription_succeeded","data":{},"channel":"topic-complete"}
pusher.min.js:8 Pusher : No callbacks on topic-complete for pusher:subscription_succeeded
pusher.min.js:8 Pusher : Event recd : {"event":"App\\Events\\User\\EstudyAcademy\\Trigger\\MarkTopicComplete","data":{"user_id":1,"topic_id":2},"channel":"topic-complete"}
pusher.min.js:8 Pusher : No callbacks on topic-complete for App\Events\User\EstudyAcademy\Trigger\MarkTopicComplete
如您所见,我确实收到“data”:{“user_id”:1,“topic_id”:2} ,但是有些方法我无法做到
警报(data.user_id);
我认为这可能是因为此错误
未捕获的TypeError:Pusher.ScriptReceivers [1]不是函数
最佳答案
我在OctoberCMS(基于Laravel的CMS)和Pusher中遇到了相同的错误。我的问题的原因是我在同一页面中无意中两次插入了pusher的js文件(pusher.js)。从他们中删除一个解决了这个问题。
关于javascript - 在Pusher中实现广播的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39827059/