Reputation: 7592
So I have 2 methods in 1 hub:
public class ChatHub : Hub
{
public void SendMessage(string name, string message)
{
Clients.All.AddMessage(name, message);
}
public void SendAnnounce(string name)
{
Clients.Others.AddMessage(name);
}
}
How do you properly use 2 methods together in 1 hub in client side javascript?
I have this in javascript,
for SendMessage(string name, string message) hub method:
var message = $("#txtMessage").val();
var userid = $("#lblUsername").html();
chat.client.addMessage = function (frm, msg) {
$messages.append("[" + frm + "] " + msg);
}
invoke:
chat.server.sendMessage(userid, input);
for SendAnnounce(string name) hub method:
chat.client.addMessage = function (frm) {
$announcement.append("<div>test</div>");
}
invoke:
var userid = $("#txtUsername").val();
chat.server.announcement(userid);
But it doesn't work(server just uses the last method in my case announcement one).
It works only if I make 2 hubs and put each method in different hubs, then create different variables for each hub like this:
//Create Hub on Air
var chat = $.connection.chatHub;
var chat2 = $.connection.announcementHub;
then work with 1 method with "chat" variable and with second method with "chat2" variable.. Then it works. Like this:
chat.client.addMessage = function (frm, msg) {
$messages.append("[" + frm + "] " + msg);
}
chat2.client.addMessage = function (frm) {
$announcement.append("<div> test</div>");
});
}
What do I not understand?
Upvotes: 1
Views: 2240
Reputation: 59
I actually got This working! calling two methods in one isntance. What i dont understand is why your creating two live connections? you will only ever need one.
Upvotes: 0
Reputation: 4423
In JavaScript you can't really have method overloads. What you are doing is first declaring addMessage
to be a function with two parameters and then overwrite that with a function with one parameter. So the last one is being used
Either use methods that are named differently, e.g. addMessage
and addAnnouncement
or use a single method and check if second parameter is defined. If it is not then it is an announcement.
Upvotes: 2