| WebSync On-Demand Tutorials | WebSync Server Tutorials |
|---|---|
|
|
|
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.
Before you can start coding, you need to have the correct project references.
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.
onSuccess handler of subscribe calls.
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 Server: Basic tutorial
by replacing onSuccess and adding onSubscribersChange.
var json = fm.json; // shortcut
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));
}
}
},
...
});
You can now open the page in a couple windows to see the subscriber notifications!