我正在创建一个聊天室演示应用程序,因为我正在尝试学习信号r。我的问题是,当从服务器上的chathub类中的connect方法尝试时,我的javascript客户端函数没有被调用。
LoadChatRoomContent客户端javascript函数仅在页面启动时执行。而不是当我从服务器集线器功能中调用它时。
有什么想法吗?
客户端
<script type="text/javascript">
**View Model**
var chatViewModel = {
chat: $.connection.chatHub,
connectToLobby: function () {
this.chat.server.connect(this.userName());
},
)
$(function () {
var chat = $.connection.chatHub;
ko.applyBindings(chatViewModel);
// client side signalr functions
chat.client.newUserHasJoined = function (userName) {
//$('#chatContent').append(userName + "has joined");
chatViewModel.latestChatContent.append(userName + "has joined");
// update the users online list when a new member has joined
chatViewModel.onlineUserList.push(userName);
};
chat.client.loadChatRoomContent = new function (messageHistory, userList) {
// convert json string to javascript array so that it can be iterated.
chatViewModel.onlineUserList = $.parseJSON(userList);
//
chatViewModel.latestChatContent = $.parseJSON(messageHistory);
alert("it works");
};
$.connection.hub.start();
});
**Chat Hub**
public class ChatHub : Hub
{
List<connectedUsers> _currentUsers;
// stores up to 100 messages
List<string> _messageCache;
public ChatHub(){
_currentUsers = new List<connectedUsers>();
_messageCache = new List<string>();
}
public void Connect(string userName)
{
// add new user to the list
lock (_currentUsers)
{
_currentUsers.Add(new connectedUsers() { Id = Guid.NewGuid(), userName = userName });
}
//let other users know of the new member
Clients.AllExcept(Context.ConnectionId).newUserHasJoined(userName);
// send chat messages and current UsersList to caller only
// both objects sent as json string format.
Clients.Caller.loadChatRoomContent( new JavaScriptSerializer().Serialize(_messageCache),new JavaScriptSerializer().Serialize(_currentUsers));
}
}