0

I am building a single page app which uses sammy.js, knockout.js and SignalR. The main page (index.html) loads additional html pages into a div based upon the client side route.

I have 2 SignalR hubs, one is connected to by the initial page for server side push data and this works fine. However one of the pages which are loaded when the user navigates to it should also connect to a different hub.

In the main page I am doing the following:

window.hubReady = $.connection.hub.start()

var hub1 = $.connection.hub1;
hub1.updateReceived = function () { 
    alert('data from server');
}

window.hubReady.done(function() {
    hub1.server.start(); 
});

In the second page I have:

var hub2 = $.connection.hub2;
hub2.updateReceived = function () { 
    alert('data from server');
}

window.hubReady.done(function() {
    hub2.server.start(); 
});

However I never receive any updates in the second page.

Any idea where I am going wrong?

4

2 回答 2

1

为了从集线器接收更新,您必须在连接启动时为该集线器声明至少 1 个客户端函数。从您使用的库来看,我假设您有一个单页应用程序,因此在连接开始之前不要实例化您的 hub2 数据。

因此,一个简单的解决方法是在调用 start 之前在 hub1 客户端函数旁边声明一个 hub2 客户端函数。如果要在连接开始后添加更多客户端功能,则必须使用 .on 方法。

又名:

hub2.on("updateReceived", function () {
    alert("data from server");
});
于 2013-07-18T16:55:44.383 回答
0

我创建了一个名为 SignalR.EventAggregatorProxy 的库。它代理服务器端域事件和客户端代码。它的设计考虑到了 MVVM 和 SPA,并负责所有集线器管道。检查 wiki 以了解如何设置它。

https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki

一旦配置完成,您订阅事件所需的全部内容就是

ViewModel = function() {
   signalR.eventAggregator.subscribe(MyApp.Events.TestEvent, this.onTestEvent, this);
};

MyApp.Events.TestEvent 对应于服务器端 .NET 事件。您还可以限制哪个事件应该去哪个用户

于 2013-07-19T07:46:49.690 回答