Skip to content

SignalR JS Client Hubs (No Proxy)

davidfowl edited this page Sep 7, 2012 · 4 revisions

SignalR JavaScript Client (Hubs)

The SignalR javascript client comes in the form of a jQuery plugin.

Setup

Include the following scripts on your page:

<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR.min.js" type="text/javascript"></script>

Programming Model

$.hubConnection( url )

Creates a new connection. The url is optional. By default it points to /signalr.

  • Returns a hubConnection.

Example

var connection = $.hubConnection();

The hubConnection is a derived class of $.connection with a few new methods specific to hubs.

connection.createProxy( hubName )

  • hubName - The name of the hub to create a proxy for.

  • Returns a hub proxy.

Example

var proxy = connection.createProxy('chat');

The hub proxy

hubProxy.invoke( method, args )

  • method - The name of the method to invoke
  • args - The arguments to the method.

Example 1

var proxy = connection.createProxy('chat'),
    msg = 'hello';
proxy.invoke('send', msg);

Example 2 (Multiple parameters)

var proxy = connection.createProxy('chat'),
    msg = 'hello',
    room = 'main';
    
proxy.invoke('send', msg, room);

Example 3 (Return value)

proxy.invoke('add', 1, 2)
     .done(function(result) {
         console.log('The result is ' + result);
     });

hubProxy.on( eventName, handler(args...) )

  • eventName - The name of the event to subscribe to
  • handler(args...) - The callback to the event name

Example

var proxy = connection.createProxy('chat');
proxy.on('addMessage', function(msg) {
    console.log(msg);
});

Cross Domain Support

You can talk to SignalR servers via the jsonp transport or by using cors (not supported by all browsers).

Cross domain urls are auto detected. We'll use xhr by default if the client (your browser) supports it. Otherwise it'll fall back to jsonp longpolling.

var connection = $.hubConnection('http://localhost:8081/');

connection.start();

To use jsonp longpolling, you can specify that option explicitly:

var connection = $.hubConnection('http://localhost:8081/');

connection.start({ jsonp: true });