REST Heavyweight Callbacks

From RAD Studio
Jump to: navigation, search

Go Up to DataSnap REST

Heavyweight callbacks allow you to, from a web page, register JavaScript functions with the server, and specify in which condition you want them to be notified by specifying the Channel ID to 'listen' to. This allows a thin client to receive nearly instantaneous notifications from the server without needing to constantly issue requests to see if anything has changed/happened.

To do notifications from the server, you first need to move the server component and all server class components onto a Data Module form (or somewhere else where they will be creating only a single instance--outside of the web module). The server has broadcast and notify functions, which take in a Channel ID and a TJSONValue 'message' object. Notify takes additional parameters to specify the exact client callback to send the message to. If you want to broadcast a message whenever a Memo component is modified, add an event for modification of this component, and in it do the following:

Val := TJSONString.Create(Memo1.Text);
[DSServer].BroadcastMessage('MemoChannel', Val); //'MemoChannel' can be replaced by anything

And then in the client code add a form with a text area with the ID "tarea" (or whatever you like) and add this JavaScript code, making sure it gets executed somehow (form submit, page onload, and so on):

var channel = new ClientChannel(null, "MemoChannel"); //this matches the server's Channel ID
var callback = new ClientCallback(channel, null,
  function(jsonValue) {
    if (jsonValue != null) {
      document.getElementById("tarea").value = jsonValue;
    return true;

With this example code, you will now have a text area in your web browser that stays in sync with whatever is typed into the memo component on the server.

In XE2, JavaScript REST callbacks can now specify a list of ServerChannelNames to listen on, on top of their channel's ServerChannelName. There is an optional final parameter to the ClientCallback constructor, which is a JSON array of channel names. This can be set to an empty array or to null if you do not want to specify any additional channel names to listen on.

This is a particular necessity for JavaScript, because of the connection limit browsers impose. Note that you can simulate similar behavior by having a naming convention across all clients for their callback IDs. The server can then broadcast to a specified Channel AND callback ID (but not client). That is almost the same as the callbacks listening on their own channel. However, it prevents clients from having multiple callbacks listening on the same channel. It also restricts the server, by making it specify the parent channel.

See Also