Pregunta

I'm getting the following js error (on the line of code marked ###) when starting my app:

JavaScript runtime error: Object doesn't support property or method 'messages'

I've previously had this working without knockout, but am trying to add in knockout as I feel this will be easier to maintain in the long run. I suspect that as this is my first venture into both SignalR and Knockout, I've done something blindingly stupid, so any pointers please let me know. The mappedMessages data is fully populated, it's just when it tries to set self.messages it has the issue. Knockout 3.0.0, SignalR 1.1.3.

The full javascript code is below:

$(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
    }

    // 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) });
        self.messages(mappedMessages);
    }

    // Start the connection
    $.connection.hub.start().done(init);

    ko.applyBindings(new MessagesViewModel());
});

Thanks :)

¿Fue útil?

Solución

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);
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top