WebSync Tutorials - Frozen Mountain

WebSync 3 Tutorials


WebSync On-Demand Tutorials WebSync Server Tutorials

WebSync On-Demand: Subscribers

Need to know who's arrived and left from your channel? Want to keep a list of users handy at all times? In this tutorial, you will learn about the onSubscribersChange handler, which gives you access to event-level notifications on channels.

Prerequisites

  1. You have completed the WebSync On-Demand: Basic tutorial.

Getting subscription information in the client

To maintain an effective list of subscribers, we need an initial list of the subscribers as well as notification of partial updates to that list.

  1. An initial snapshot of the current subscribers is available in the onSuccess handler of subscribe calls.
  2. A partial update when the someone subscribes or unsubscribes is made available via the onSubscribersChange handler.

Let's illustrate this by printing a list of the current subscribers when we subscribe to the channel and printing a message whenever another client subscribes or unsubscribes.

Modify the HTML page created in the WebSync On-Demand: Basic tutorial by replacing onSuccess and adding onSubscribersChange.

client.subscribe({
    channel: '/test',
    onSuccess: function(args) { // optional
        util.log('Subscribed!');
        var subscribedClients = args.subscribedClients['/test'];
        for (var i = 0; i < subscribedClients.length; i++) {
            var subscribedClient = subscribedClients[i];
            util.log('Currently subscribed: client with id ' + subscribedClient.id +
                ' and bound records ' + json.stringify(subscribedClient.boundRecords));
        }
    },
    onSubscribersChange: function(args) { // optional
        var change = args.change;
        for (var i = 0; i < change.clients.length; i++) {
            var changeClient = change.clients[i];
            if (change.type == 'subscribe') {
                util.log('Just subscribed: client with id ' + changeClient.id +
                    ' and bound records ' + json.stringify(changeClient.boundRecords));
            } else {
                util.log('Just unsubscribed: client with id ' + changeClient.id +
                    ' and bound records ' + json.stringify(changeClient.boundRecords));
            }
        }
    },
    ...
});

Testing

You can now open the page in a couple windows to see the subscriber notifications!