Friday, 31 August 2012

Calling a SignalR server function on page load

I was working on the demo for next blog post. In the demo, I needed to call a SignalR server method on the page load (i.e., jQuery’s ready event). The only thing I kept in mind was, the connection should be started before I call the method. I added the following piece of code to the ready event and opened the page on a browser:

var proxy = $.connection.myHub;

Unfortunately, it didn’t work. I thought that there might be some JavaScript errors with this small piece of code, which I failed to spot by looking at the code. I opened the developer tools of Opera browser and refreshed the page. Execution of JavaScript was halted at the following statement of the dynamically generated /signalr/hubs script:

Error statement

I found the following in the error list:

After reading and analysing a bit on the above error, I inferred that the start() function is not a synchronous function. I invoked hub’s function before SignalR established the connection. Error message in the first screenshot suggests a solution to this issue. It is mentioned there to use .start().done() or .start().fail() to run logic after the connection started. I modified the code to:

var proxy = $.connection.myHub;
$.connection.hub.start().done(  function() {

I opened the page on the browser and as expected, I got the result. I thought of using an approach that I already knew, using pipe() to register the callback logic. I again modified the code to:

var proxy = $.connection.myHub;
$.connection.hub.start().pipe(  function() {

It didn’t disappoint me. I got what I wanted.

I visited the SignalR JS Client documentation page on GitHub to learn more about SignalR client script. I learnt another way of wiring up the callback function on this page. This approach is the simpler than both of the above approaches. We can register the callback to the start function itself as follows:

$.connection.hub.start( function() {

I tried it out and got the result.
If you get to know any other approach, you may share it through comments.

Happy coding!

No comments:

Post a Comment

Note: only a member of this blog may post a comment.