You should use the viewModel object in the SignalR client methods. Currently, you're trying to use a variable called self
, but that variable isn't available in that SignalR client method scope. I have updated your code into a version which I believe should solve your problem, doing as few changes as possible.
$(function () {
var messageHub = $.connection.messageHubMini;
function init() { }
function Message(data) {
this.Operator = ko.observable(data.Operator);
this.text = ko.observable(data.Text);
}
function MessagesViewModel() {
// Data
var self = this;
self.messages = ko.observableArray([]); //### message on this line
}
var viewModel = new MessagesViewModel();
// Add a client-side hub method that the server will call
messageHub.client.updateMessages = function (data) {
var mappedMessages = $.map(data, function (item) { return new Message(item) });
viewModel.messages(mappedMessages);
}
// Start the connection
$.connection.hub.start().done(init);
ko.applyBindings(viewModel);
});