Skip to content

JavaScript Server Events Client

Demis Bellot edited this page Oct 25, 2016 · 16 revisions

This page has moved to docs.servicestack.net


Like ServiceStack's other JavaScript interop libraries, the client bindings for ServiceStack's Server Events is in ServiceStack's JavaScript client bindings /js/ss-utils.js that's embedded in ServiceStack.dll and available from any page with:

<script src="/js/ss-utils.js"></script>

To configure Server Sent Events on the client create a native EventSource object with:

var source = new EventSource(
    '/event-stream?channel=channel&t=' + new Date().getTime());

The default url /event-stream can be modified with ServerEventsFeature.StreamPath

As this is the native EventSource object, you can interact with it directly, e.g. you can add custom error handlers with:

source.addEventListener('error', function (e) { 
        console.log("ERROR!", e); 
    }, false);

The ServiceStack binding itself is just a thin jQuery plugin that extends EventSource, e.g:

$(source).handleServerEvents({
    handlers: {
        onConnect: function (subscription) {
            console.log("You've connected! welcome " + u.displayName);
        },
        onJoin: function (user) {
            console.log("Welcome, " + user.displayName);
        },
        onLeave: function (user) {
            console.log(user.displayName + " has left the building");
        },
        //... Register custom handlers
    },
    receivers: { 
        //... Register any receivers
    },
    // fired after every message
    success: function (selector, msg, json) {
        console.log(selector, msg, json);
    },
});

ServiceStack Server Events has 3 built-in events sent during a subscriptions life-cycle:

  • onConnect - sent when successfully connected, includes the subscriptions private subscriptionId as well as heartbeat and unregister urls that's used to automatically setup periodic heartbeats.
  • onJoin - sent when a new user joins the channel.
  • onLeave - sent when a user leaves the channel.

The onJoin/onLeave events can be turned off with ServerEventsFeature.NotifyChannelOfSubscriptions=false.

Selectors

A selector is a string that identifies what should handle the message, it's used by the client to route the message to different handlers. The client bindings in /js/ss-utils.js supports 4 different handlers out of the box:

Global Event Handlers

To recap Declarative Events allow you to define global handlers on a html page which can easily be applied on any element by decorating it with data-{event}='{handler}' attribute, eliminating the need to do manual bookkeeping of DOM events.

The example below first invokes the paintGreen handler when the button is clicked and fires the paintRed handler when the button loses focus:

$(document).bindHandlers({
    paintGreen: function(){
        $(this).css("background","green");
    }, 
    paintRed: function(){
        $(this).css("background","red");
    }, 
});
<button id="btnPaint" data-click="paintGreen" data-focusout="paintRed">
    Paint Town
</button>

The selector to invoke a global event handler is:

cmd.{handler}

Where {handler} is the name of the handler you want to invoke, e.g cmd.paintGreen. When invoked from a server event the message (deserialized from JSON) is the first argument, the Server Sent DOM Event is the 2nd argument and this by default is assigned to document.body.

function paintGreen(msg /* JSON object msg */, e /*SSE Event*/){
    this // HTML Element or document.body
    $(this).css("background","green");
},

Handling Messages with the Default Selector

All IServerEvents Notify API's includes overloads for sending messages without a selector that by convention will take the format cmd.{TypeName}.

As they're prefixed with cmd.* these events can be handled with a handler based on Message type name, e.g:

$(source).handleServerEvents({
    handlers: {
        CustomType: function (msg, e) { ... },
        SetterType: function (msg, e) { ... }
    },
});

Which will be called when messages are sent without a selector, e.g:

public class MyServices : Service
{
    public IServerEvents ServerEvents { get; set; }

    public void Any(Request request)
    {
        ServerEvents.NotifyChannel("home", new CustomType { ... });
        ServerEvents.NotifyChannel("home", new SetterType { ... });
    }
}

Postfix jQuery selector

All server event handler options also support a postfix jQuery selector for specifying what each handler should be bound to with a $ followed by the jQuery selector, e.g:

cmd.{handler}${jQuerySelector}

A concrete example for calling the above API would be:

cmd.paintGreen$#btnPaint

Which will bind this to the #btnSubmit HTML Element, retaining the same behavior as if it were called with data-click="paintGreen".

Note: Spaces in jQuery selectors need to be encoded with %20

Modifying CSS via jQuery

As it's a popular use-case Server Events also has native support for modifying CSS properties on any jQuery with:

css.{propertyName}${jQuerySelector} {propertyValue}

Where the message is the property value, which roughly translates to:

$({jQuerySelector}).css({propertyName}, {propertyValue})

When no jQuery selector is specified it falls back to document.body by default.

/css.background #eceff1

Some other examples include:

/css.background$#top #673ab7   // $('#top').css('background','#673ab7')
/css.font$li bold 12px verdana // $('li').css('font','bold 12px verdana')
/css.visibility$a,img hidden   // $('a,img').css('visibility','#673ab7')
/css.visibility$a%20img hidden // $('a img').css('visibility','hidden')

jQuery Events

A popular approach in building loosely-coupled applications is to have components interact with each other by raising events. It's similar to channels in Pub/Sub where interested parties can receive and process custom events on components they're listening on. jQuery supports this model by simulating DOM events that can be raised with $.trigger().

You can subscribe to custom events in the same way as normal DOM events, e.g:

$(document).on('customEvent', function(event, arg, msgEvent){
    var target = event.target;
});

The selector to trigger this event is:

trigger.customEvent arg
trigger.customEvent$#btnPaint arg

Where if no jQuery selector is specified it defaults to document. These selectors are equivalent to:

$(document).trigger('customEvent', 'arg')
$("#btnPaint").trigger('customEvent', 'arg')

Receivers

In programming languages based on message-passing like Smalltalk and Objective-C invoking a method is done by sending a message to a receiver. This is conceptually equivalent to invoking a method on an instance in C# where both these statements are roughly equivalent:

// Objective-C
[receiver method:argument]
// C#
receiver.method(argument)

Support for receivers is available in the following format:

{receiver}.{target} {msg}

Registering Receivers

Registering a receiver can be either be done by adding it to the global $.ss.eventReceivers map with the object instance and the name you want it to be exported as. E.g. The window and document global objects can be setup to receive messages with:

$.ss.eventReceivers = { 
    "window": window, 
    "document": document 
};

Once registered you can set any property or call any method on a receiver with:

document.title New Window Title
window.location http://google.com

Where if {target} was a function it will be invoked with the message, otherwise its property will be set. By default when no {jQuerySelector} is defined, this is bound to the receiver instance.

The alternative way to register a receiver is at registration with:

$(source).handleServerEvents({
  ...
  receivers: {
    tv: {
      watch: function (id) {
        if (id.indexOf('youtu.be') >= 0) {
            var v = $.ss.splitOnLast(id, '/')[1];
            $("#tv").html(templates.youtube.replace("{id}", v)).show();
        } else {
            $("#tv").html(templates.generic.replace("{id}", id)).show();
        }
      },
      off: function () {
        $("#tv").hide().html("");
      }
   }
}
});

This registers a custom tv receiver that can now be called with:

tv.watch http://youtu.be/518XP8prwZo
tv.watch https://servicestack.net/img/logo-220.png
tv.off

Un Registering a Receiver

As receivers are maintained in a simple map, they can be disabled at anytime with:

$.ss.eventReceivers["window"] = null; 

and re-enabled with:

$.ss.eventReceivers["window"] = window;

Whilst Named Receivers are used to handle messages sent to a specific namespaced selector, the client also supports registering a Global Receiver for handling messages sent with the special cmd.* selector.

UpdateSubscriber APIs

You can use any of the APIs below in the ss-utils JavaScript library to update an active Subscriptions Channels:

$.ss.updateSubscriber({ 
    SubscribeChannels: "chan1,chan2",
    UnsubscribeChannels: "chan3,chan4"
});

$.ss.subscribeToChannels(["chan1","chan2"], response => ..., error => ...);
$.ss.unsubscribeFromChannels(["chan3","chan4"], response => ..., error => ...);

ServerEvent JavaScript Examples

Gistlyn is a C# Gist IDE for creating, running and sharing stand-alone, executable C# snippets.

Live Demo: http://gistlyn.com

React Chat is a port of ServiceStack Chat ES5, jQuery Server Events demo into a TypeScript, React and Redux App:

A network-enhanced version of the stand-alone Time Traveller Shape Creator that allows users to connect to and watch other users using the App in real-time similar to how users can use Remote Desktop to watch another computer's screen:

Live demo: http://redux.servicestack.net

Feature-rich Single Page Chat App, showcasing Server Events support in 170 lines of JavaScript!

Built with React Desktop Apps VS.NET template and packaged into a native Desktop App for Windows and OSX - showcasing synchronized real-time control of multiple Windows Apps:

Downloads for Windows, OSX, Linux and Web



  1. Getting Started

    1. Creating your first project
    2. Create Service from scratch
    3. Your first webservice explained
    4. Example Projects Overview
    5. Learning Resources
  2. Designing APIs

    1. ServiceStack API Design
    2. Designing a REST-ful service with ServiceStack
    3. Simple Customer REST Example
    4. How to design a Message-Based API
    5. Software complexity and role of DTOs
  3. Reference

    1. Order of Operations
    2. The IoC container
    3. Configuration and AppSettings
    4. Metadata page
    5. Rest, SOAP & default endpoints
    6. SOAP support
    7. Routing
    8. Service return types
    9. Customize HTTP Responses
    10. Customize JSON Responses
    11. Plugins
    12. Validation
    13. Error Handling
    14. Security
    15. Debugging
    16. JavaScript Client Library (ss-utils.js)
  4. Clients

    1. Overview
    2. C#/.NET client
      1. .NET Core Clients
    3. Add ServiceStack Reference
      1. C# Add Reference
      2. F# Add Reference
      3. VB.NET Add Reference
      4. Swift Add Reference
      5. Java Add Reference
    4. Silverlight client
    5. JavaScript client
      1. Add TypeScript Reference
    6. Dart Client
    7. MQ Clients
  5. Formats

    1. Overview
    2. JSON/JSV and XML
    3. HTML5 Report Format
    4. CSV Format
    5. MessagePack Format
    6. ProtoBuf Format
  6. View Engines 4. Razor & Markdown Razor

    1. Markdown Razor
  7. Hosts

    1. IIS
    2. Self-hosting
    3. Messaging
    4. Mono
  8. Security

    1. Authentication
    2. Sessions
    3. Restricting Services
    4. Encrypted Messaging
  9. Advanced

    1. Configuration options
    2. Access HTTP specific features in services
    3. Logging
    4. Serialization/deserialization
    5. Request/response filters
    6. Filter attributes
    7. Concurrency Model
    8. Built-in profiling
    9. Form Hijacking Prevention
    10. Auto-Mapping
    11. HTTP Utils
    12. Dump Utils
    13. Virtual File System
    14. Config API
    15. Physical Project Structure
    16. Modularizing Services
    17. MVC Integration
    18. ServiceStack Integration
    19. Embedded Native Desktop Apps
    20. Auto Batched Requests
    21. Versioning
    22. Multitenancy
  10. Caching

  11. Caching Providers

  12. HTTP Caching 1. CacheResponse Attribute 2. Cache Aware Clients

  13. Auto Query

  14. Overview

  15. Why Not OData

  16. AutoQuery RDBMS

  17. AutoQuery Data 1. AutoQuery Memory 2. AutoQuery Service 3. AutoQuery DynamoDB

  18. Server Events

    1. Overview
    2. JavaScript Client
    3. C# Server Events Client
    4. Redis Server Events
  19. Service Gateway

    1. Overview
    2. Service Discovery
  20. Encrypted Messaging

    1. Overview
    2. Encrypted Client
  21. Plugins

    1. Auto Query
    2. Server Sent Events
    3. Swagger API
    4. Postman
    5. Request logger
    6. Sitemaps
    7. Cancellable Requests
    8. CorsFeature
  22. Tests

    1. Testing
    2. HowTo write unit/integration tests
  23. ServiceStackVS

    1. Install ServiceStackVS
    2. Add ServiceStack Reference
    3. TypeScript React Template
    4. React, Redux Chat App
    5. AngularJS App Template
    6. React Desktop Apps
  24. Other Languages

    1. FSharp
      1. Add ServiceStack Reference
    2. VB.NET
      1. Add ServiceStack Reference
    3. Swift
    4. Swift Add Reference
    5. Java
      1. Add ServiceStack Reference
      2. Android Studio & IntelliJ
      3. Eclipse
  25. Amazon Web Services

  26. ServiceStack.Aws

  27. PocoDynamo

  28. AWS Live Demos

  29. Getting Started with AWS

  30. Deployment

    1. Deploy Multiple Sites to single AWS Instance
      1. Simple Deployments to AWS with WebDeploy
    2. Advanced Deployments with OctopusDeploy
  31. Install 3rd Party Products

    1. Redis on Windows
    2. RabbitMQ on Windows
  32. Use Cases

    1. Single Page Apps
    2. HTML, CSS and JS Minifiers
    3. Azure
    4. Connecting to Azure Redis via SSL
    5. Logging
    6. Bundling and Minification
    7. NHibernate
  33. Performance

    1. Real world performance
  34. Other Products

    1. ServiceStack.Redis
    2. ServiceStack.OrmLite
    3. ServiceStack.Text
  35. Future

    1. Roadmap
Clone this wiki locally