- Notifications
You must be signed in to change notification settings - Fork1.6k
JavaScript Server Events Client
This page has moved todocs.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 inServiceStack.dll and available from any page with:
<scriptsrc="/js/ss-utils.js"></script>
To configure Server Sent Events on the client create anative EventSource object with:
varsource=newEventSource('/event-stream?channel=channel&t='+newDate().getTime());
The default url
/event-streamcan be modified withServerEventsFeature.StreamPath
As this is the nativeEventSource 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 extendsEventSource, 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 messagesuccess: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
subscriptionIdas 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.
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:
To recapDeclarative Events allow you to define global handlers on a html page which can easily be applied on any element by decorating it withdata-{event}='{handler}' attribute, eliminating the need to do manual bookkeeping of DOM events.
The example below first invokes thepaintGreen handler when the button is clicked and fires thepaintRed handler when the button loses focus:
$(document).bindHandlers({paintGreen:function(){$(this).css("background","green");},paintRed:function(){$(this).css("background","red");},});
<buttonid="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.gcmd.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 andthis by default is assigned todocument.body.
functionpaintGreen(msg/* JSON object msg */,e/*SSE Event*/){this// HTML Element or document.body$(this).css("background","green");},
AllIServerEvents Notify API's includesoverloads for sending messages without a selector that by convention will take the formatcmd.{TypeName}.
As they're prefixed withcmd.* these events can be handled with a handlerbased 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:
publicclassMyServices:Service{publicIServerEventsServerEvents{get;set;}publicvoidAny(Requestrequest){ServerEvents.NotifyChannel("home",newCustomType{ ...});ServerEvents.NotifyChannel("home",newSetterType{ ...});}}
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$#btnPaintWhich will bindthis to the#btnSubmit HTML Element, retaining the same behavior as if it were called withdata-click="paintGreen".
Note: Spaces in jQuery selectors need to be encoded with
%20
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 todocument.body by default.
/css.background #eceff1Some 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')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){vartarget=event.target;});
The selector to trigger this event is:
trigger.customEvent argtrigger.customEvent$#btnPaint argWhere if no jQuery selector is specified it defaults todocument. These selectors are equivalent to:
$(document).trigger('customEvent','arg')$("#btnPaint").trigger('customEvent','arg')
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[receivermethod:argument]
// C#receiver.method(argument)
Support for receivers is available in the following format:
{receiver}.{target} {msg}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. Thewindow anddocument 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 Titlewindow.location http://google.comWhere 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 thereceiver 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){varv=$.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 customtv receiver that can now be called with:
tv.watch http://youtu.be/518XP8prwZotv.watch https://servicestack.net/img/logo-220.pngtv.offAs 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 aGlobal Receiver for handling messages sent with the specialcmd.* selector.
You can use any of the APIs below in thess-utils JavaScript libraryto 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=> ...);
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 ofServiceStack Chat ES5, jQuery Server Eventsdemo into aTypeScript,React andRedux App:
A network-enhanced version of thestand-alone Time Traveller Shape Creatorthat allows users toconnect to andwatch other users using the App in real-time similarto 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 withReact Desktop AppsVS.NET template and packaged into a native Desktop App for Windows and OSX - showcasing synchronizedreal-time control of multiple Windows Apps:
Downloads forWindows, OSX, Linux and Web
- Why ServiceStack?
- Important role of DTOs
- What is a message based web service?
- Advantages of message based web services
- Why remote services should use separate DTOs
Getting Started
Designing APIs
Reference
Clients
Formats
View Engines4.Razor & Markdown Razor
Hosts
Security
Advanced
- Configuration options
- Access HTTP specific features in services
- Logging
- Serialization/deserialization
- Request/response filters
- Filter attributes
- Concurrency Model
- Built-in profiling
- Form Hijacking Prevention
- Auto-Mapping
- HTTP Utils
- Dump Utils
- Virtual File System
- Config API
- Physical Project Structure
- Modularizing Services
- MVC Integration
- ServiceStack Integration
- Embedded Native Desktop Apps
- Auto Batched Requests
- Versioning
- Multitenancy
Caching
Auto Query
AutoQuery Data1.AutoQuery Memory2.AutoQuery Service3.AutoQuery DynamoDB
Server Events
Service Gateway
Encrypted Messaging
Plugins
Tests
ServiceStackVS
Other Languages
Amazon Web Services
Deployment
Install 3rd Party Products
Use Cases
Performance
Other Products
Future




