/src/Microsoft.AspNet.SignalR.Core/Scripts/hubs.js

https://github.com/belanger-simon/SignalR · JavaScript · 90 lines · 50 code · 17 blank · 23 comment · 9 complexity · 152bf689dc07bd270c05803d4b172542 MD5 · raw file

  1. /*!
  2. * ASP.NET SignalR JavaScript Library v1.0.0
  3. * http://signalr.net/
  4. *
  5. * Copyright Microsoft Open Technologies, Inc. All rights reserved.
  6. * Licensed under the Apache 2.0
  7. * https://github.com/SignalR/SignalR/blob/master/LICENSE.md
  8. *
  9. */
  10. /// <reference path="..\..\SignalR.Client.JS\Scripts\jquery-1.6.4.js" />
  11. /// <reference path="jquery.signalR.js" />
  12. (function ($, window) {
  13. /// <param name="$" type="jQuery" />
  14. "use strict";
  15. if (typeof ($.signalR) !== "function") {
  16. throw new Error("SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/hubs.");
  17. }
  18. var signalR = $.signalR;
  19. function makeProxyCallback(hub, callback) {
  20. return function () {
  21. // Call the client hub method
  22. callback.apply(hub, $.makeArray(arguments));
  23. };
  24. }
  25. function registerHubProxies(instance, shouldSubscribe) {
  26. var key, hub, memberKey, memberValue, subscriptionMethod;
  27. for (key in instance) {
  28. if (instance.hasOwnProperty(key)) {
  29. hub = instance[key];
  30. if (!(hub.hubName)) {
  31. // Not a client hub
  32. continue;
  33. }
  34. if (shouldSubscribe) {
  35. // We want to subscribe to the hub events
  36. subscriptionMethod = hub.on;
  37. }
  38. else {
  39. // We want to unsubscribe from the hub events
  40. subscriptionMethod = hub.off;
  41. }
  42. // Loop through all members on the hub and find client hub functions to subscribe/unsubscribe
  43. for (memberKey in hub.client) {
  44. if (hub.client.hasOwnProperty(memberKey)) {
  45. memberValue = hub.client[memberKey];
  46. if (!$.isFunction(memberValue)) {
  47. // Not a client hub function
  48. continue;
  49. }
  50. subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue));
  51. }
  52. }
  53. }
  54. }
  55. }
  56. $.hubConnection.prototype.createHubProxies = function () {
  57. var proxies = {};
  58. this.starting(function () {
  59. // Register the hub proxies as subscribed
  60. // (instance, shouldSubscribe)
  61. registerHubProxies(proxies, true);
  62. this._registerSubscribedHubs();
  63. }).disconnected(function () {
  64. // Unsubscribe all hub proxies when we "disconnect". This is to ensure that we do not re-add functional call backs.
  65. // (instance, shouldSubscribe)
  66. registerHubProxies(proxies, false);
  67. });
  68. /*hubs*/
  69. return proxies;
  70. };
  71. signalR.hub = $.hubConnection("{serviceUrl}", { useDefaultPath: false });
  72. $.extend(signalR, signalR.hub.createHubProxies());
  73. }(window.jQuery, window));