0

I want to use a SignalR hub in a layout and in a partial page. Here it is described to use hub.start and done functions.

So I have two script blocks in my html page where i want to use SignalR:

<script>
    $(document).ready(function () {
        window.hubReady = $.connection.hub.start();
        window.hubReady.done(function () {
            ...
        });
</script>

<script>
    $(document).ready(function(e) {
        window.hubReady.done(function() {
            ...
        });
    });
</script>

In the second script block it says that windows.hubReady.done can't be executed because it's undefined.

EDIT: block 2 is executed before block 1. But why?

daniel
  • 34,281
  • 39
  • 104
  • 158

2 Answers2

2

My guess is that the second callback is executed before the first, and if that's the case then window.hubReady is null since it's the first callback that initializes window.hubReady.

I would suggest that you don't create a global reference to your hub and instead reference it directly, ie:

<script>
    $(document).ready(function(e) {
        $.connection.hub.connected(function() {
            ...
        });
    });
</script>

(If this doesn't work then I suspect your hub named "hub" isn't defined on the server, but that's a different issue)

Onkelborg
  • 3,927
  • 1
  • 19
  • 22
  • the second callback is executed before the first. So line 1100 is executed before line 76. I don't understand why. – daniel Feb 25 '13 at 11:39
  • i think your guess is that the second callback is executed _BEFORE_ the first? – daniel Feb 25 '13 at 11:40
  • The lines are executed in order, however, the functions aren't necessarily executed in the order of the document since they are callbacks. It's jQuery that decides the order of execution. – Onkelborg Feb 25 '13 at 11:52
  • So i don't know the order what is bad. Is there something in SignalR to test if the hub is already started? – daniel Feb 25 '13 at 11:58
  • ok, new question on this problem: http://stackoverflow.com/questions/15066693/signalr-check-if-hub-already-started – daniel Feb 25 '13 at 12:12
  • Check the documentation, there are event's you can hook up directly to you hub – Onkelborg Feb 25 '13 at 12:46
  • can you be more explicit? connected is not a function by the way – daniel Feb 25 '13 at 13:15
  • You can attach events with standard jQuery-syntax: .bind("onStart", function(e) {}); – Onkelborg Feb 25 '13 at 15:24
0

i solved the problem by not calling $(document).ready(function(e) but $(window).load(function() in my partial html. $(window).load(function() is called second then.

daniel
  • 34,281
  • 39
  • 104
  • 158
  • Just a warning: it's not very reliable, it may break in the future if something changes, ex. jQuery-internals, the order of your scripts etc. – Onkelborg Feb 26 '13 at 08:26