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; $.connection.hub.start(); proxy.server.functionCall();
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:
I found the following in the error list:
var proxy = $.connection.myHub; $.connection.hub.start().done( function() { proxy.server.functionCall() });
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() { proxy.server.functionCall() });
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() { proxy.server.functionCall() });
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.