Detecting when signalR hub is ready after hub.start()

血红的双手。 提交于 2019-12-11 19:34:45

问题


I have a parent and child viewModel. The parent viewmodel starts the signalR connection:

$.connection.hub.start()

The child viewmodel - one that loads only when the user accesses chat - does the following:

chat.server.addUserToChat(self.currentUsername()).done(function() {
    alert('added');
});

The problem is, the child call is happening before the parent call. I can fix this with a setTimeOut of 1 second, but ideally I could do something like this:

$.connection.hub.ready(function(){chat.server.addUserToChat(self.currentUsername()).done(function() {
        alert('added');
    });});

Is there anything like this in signalR? Or do I need to use timeouts / pub/sub between viewmodels?


回答1:


This seems to be more an issue of structuring your application. You can store the deferred object returned by hub.start() in some global object and access it in your child viewmodel:

window.chatApp = {
    hubConnector: $.connection.hub.start()
};

// in your child viewmodel
chatApp.hubConnector.done(function () {
    chat.server.addUserToChat(self.currentUsername()).done(function () {
        alert('added');
    });
});



回答2:


Try this

$.connection.hub.start().done(function () {
  // hub is now ready
  chat.server.addUserToChat(self.currentUsername()).done(function() {
    alert('added');
  });
});


来源:https://stackoverflow.com/questions/21080143/detecting-when-signalr-hub-is-ready-after-hub-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!