Signalr Javascript客户端代理多个事件
问题描述:
我检查了signalr hubs api guide javascript client proxy文档。我知道如何在不覆盖函数的情况下追加相同的客户端功能。但是当涉及到启动功能时,我无法找到任何有关它的信息。只是一些JavaScript技巧。所以我创建了一个非常简单的例子。在这里我做什么,我想做的事情:Signalr Javascript客户端代理多个事件
这里一个很简单的轮毂:
[HubName("exampleHub")]
public class ExampleHub : Hub
{
public void ExampleMessage()
{
this.Clients.All.message("This message goes to two different client method!");
}
}
这里是JavaScript文件:
function ExampleViewModel(exampleHubProxy) {
var self = this;
self.init = function() {
exampleHubProxy.invoke('exampleMessage');
};
};
$(function() {
var connection = $.hubConnection();
var exampleHubProxy = connection.createHubProxy('exampleHub');
var exampleViewModel = new ExampleViewModel(exampleHubProxy);
exampleHubProxy.on('message', function (clientEvent1) {
console.log(clientEvent1);
});
exampleHubProxy.on('message', function (clientEvent2) {
console.log(clientEvent2);
});
$.connection.hub.start().done(exampleViewModel.init);
})
和输出的两倍“这条消息去以两种不同的客户端方法!'登录。一切都如我所料。而且这就是我想在生成的代理这样的:
$(function() {
var exampleHubProxy = $.connection.exampleHub;
var exampleViewModel = new ExampleViewModel(exampleHubProxy);
var anotherViewModel = new AnotherViewModel(exampleHubProxy);
//I know this is not valid. I am looking for something like this.
exampleHubProxy.client.message += function (clientEvent1) {
console.log(clientEvent1);
};
exampleHubProxy.client.message += function (clientEvent2) {
console.log(clientEvent2);
};
//Real question starts here
//This is what I can't do in without generated proxies!
$.connection.hub.start+=exampleViewModel.init;
$.connection.hub.start+=anotherViewModel.init;
$.connection.hub.start();
})
所以,问题的根本原因是,我有不同的视图模型JavaScript文件,我应该在同一个页面启动它们。这意味着我必须将$ .connection.hub.start()函数携带到页面底部的某个位置。但这些JavaScript文件没有关系,所以当一个工作,其他人可能不会。当一个JavaScript文件启动集线器时,其他人可能想修改客户端对象并重新启动它。所以AFAIK这不是一个好主意。我也检查了this question但它没有给我一个很好的解决方案。
答
使用start()方法返回一个promise并添加多个处理程序以实现它。
承诺是一个jQuery Deferred对象:http://api.jquery.com/category/deferred-object/
$(function() {
var exampleHubProxy = $.connection.exampleHub;
var exampleViewModel = new ExampleViewModel(exampleHubProxy);
var anotherViewModel = new AnotherViewModel(exampleHubProxy);
exampleHubProxy.on('message', function (clientEvent1) {
console.log(clientEvent1);
});
exampleHubProxy.on('message', function (clientEvent2) {
console.log(clientEvent2);
});
//Real question starts here
var startPromise = $.connection.hub.start();
// start() returns a promise
startPromise.then(exampleViewModel.init);
startPromise.then(anotherViewModel.init);
$.connection.hub.start();
});
谢谢你帮助我很多!现在我可以创建像我想象的那样的架构。我正在寻找这一个星期,并不知道这很容易。 –
如何链接这些承诺也很好,例如:'startPromise.then(exampleViewModel.init).then(anotherViewModel.init);' –