I'm making a project with laravel and pusher.
When I trigger the event from server like this:
$pusher = new Pusher(env('PUSHER_APP_KEY'), env('PUSHER_APP_SECRET'), env('PUSHER_APP_ID'), array('cluster' => env('PUSHER_CLUSTER')));
$pusher->trigger('presence-chat', 'MessageSent', array('message' => 'mensaje enviado'));
I can listen it with that:
var channel = pusher.subscribe('presence-chat');
channel.bind('MessageSent', function(data) {
comprobar_mensajes();
});
I'm using a presence channel and now I want to make a count of the online users so I'm trying to use the event pusher:subscription_succeeded:
channel.bind('pusher:subscription_succeeded', function(members) {
$('#count-users').text(members.count);
});
When you load the page the count works correctly but if another user connects the count of the previous user front end is not being updated. I tried to trigger an extra event:
channel.bind('pusher:subscription_succeeded', function(members) {
$('#count-users').text(members.count);
channel.trigger('client-test',{ your: data });
});
channel.bind('client-test', function(data) {
$('#count-users').text(members.count);
alert('recibido');
});
But I never get the alert.
As well as binding to the pusher:subscription_succeeded event you should also bind to the pusher:member_added and pusher:member_removed events. Only the user initiating the connection receives the susbscription_succeeded event. The other two events are broadcast to all connected users.
By binding to added and removed events you can then determine when member counts have been incremented or decremented.
You can check this as follows:
channel.bind('pusher:subscription_succeeded', function(members) {
console.log(members.count);
});
channel.bind('pusher:member_added', function(member) {
console.log(channel.members.count);
});
channel.bind('pusher:member_removed', function(member) {
console.log(channel.members.count);
});
Full reference can be found here: https://pusher.com/docs/client_api_guide/client_presence_channels#channel_members