Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

JavaScript Server Events Client

Demis Bellot edited this pageOct 25, 2016 ·16 revisions

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-stream can 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 privatesubscriptionId 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 withServerEventsFeature.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 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");},

Handling Messages with the Default Selector

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{ ...});}}

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 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

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 todocument.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){vartarget=event.target;});

The selector to trigger this event is:

trigger.customEvent argtrigger.customEvent$#btnPaint arg

Where if no jQuery selector is specified it defaults todocument. 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[receivermethod: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. 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.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 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.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 aGlobal Receiver for handling messages sent with the specialcmd.* selector.

UpdateSubscriber APIs

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=> ...);

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 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



  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 Engines4.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 Caching1.CacheResponse Attribute2.Cache Aware Clients

  13. Auto Query

  14. Overview

  15. Why Not OData

  16. AutoQuery RDBMS

  17. AutoQuery Data1.AutoQuery Memory2.AutoQuery Service3.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


[8]ページ先頭

©2009-2025 Movatter.jp