Pusher事件被触发两次。

5

我正在使用Pusher(pusher.com)来触发通知,让所有已登录的客户端在管理员发送通知时收到通知。

由于某种原因,事件会触发两次,尽管我只触发一次。

客户端订阅代码:

var handleToastrListener = function() {

     var pusher = new Pusher("913284db62a0cc237db4");
     var channel = pusher.subscribe('toastr-channel');

           channel.bind('new-toast', function(data) {

            toastr.options = data.options;
            var $toast = toastr[data.scf](data.msg, data.title);

           return true;

           });  
   }

       handleToastrListener();

服务器端发表代码(使用推动包的PHP):

 $pusher = new Pusher(PUSHER_KEY, PUSHER_SECRET, PUSHER_APP_ID);
 $pusher->trigger('toastr-channel', 'new-toast', $input );

Pusher调试控制台显示只收到了一条消息。 然而,pusher-js的Javascript日志显示了两条消息。
Pusher : Event recd : {"event":"new-toast","data":{"options":{"positionClass":"toast-top-right","onclick":"","showDuration":"1000","hideDuration":"1000","timeOut":"5000","extendedTimeOut":"1000","showEasing":"swing","hideEasing":"linear","showMethod":"fadeIn","hideMethod":"fadeOut"},"title":"Toastr Notifications","msg":"Gnome & Growl type non-blocking notifications","scf":"success"},"channel":"toastr-channel"} app.js:143
Pusher : Event recd : {"event":"new-toast","data":{"options":{"positionClass":"toast-top-right","onclick":"","showDuration":"1000","hideDuration":"1000","timeOut":"5000","extendedTimeOut":"1000","showEasing":"swing","hideEasing":"linear","showMethod":"fadeIn","hideMethod":"fadeOut"},"title":"Toastr Notifications","msg":"Gnome & Growl type non-blocking notifications","scf":"success"},"channel":"toastr-channel"}

进一步查看后,我发现订阅出现了两次,尽管我只调用了一次:

Pusher : Event sent : {"event":"pusher:subscribe","data":{"channel":"toastr-channel"}} app.js:143
Pusher : Event recd : {"event":"pusher_internal:subscription_succeeded","data":{},"channel":"toastr-channel"} app.js:143
Pusher : No callbacks on toastr-channel for pusher:subscription_succeeded app.js:143
Pusher : State changed : connecting -> connected app.js:143
Pusher : Event sent : {"event":"pusher:subscribe","data":{"channel":"toastr-channel"}} app.js:143
Pusher : Event recd : {"event":"pusher_internal:subscription_succeeded","data":{},"channel":"toastr-channel"} app.js:143
Pusher : No callbacks on toastr-channel for pusher:subscription_succeeded 
2个回答

6

有两件事情你一定要看一下,并根据需要更新你的问题:

  1. Pusher调试控制台 - 这个事件在那里显示了两次吗?
  2. pusher-js JavaScript日志记录 - 这个事件被记录为incoming两次了吗?

另一个常见的问题是有时事件可能已经绑定了两次,因此有两个回调函数。但是,你的代码并没有表明发生了这种情况。


调试控制台只显示一个消息,但日志记录显示两个。我已相应更新了我的问题。 - Matanya
3
好的,这有点尴尬。原来我在代码中不同的位置调用了两次句柄。 - Matanya

0
解决这个问题,你需要在绑定之前解绑该通道。
pusherClient.subscribe(1234);
pusherClient.bind(1234);
pusherClient.bind("incoming-message", (text) => {
  console.log(text);
});

点击这里获取更多信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接