0

我有以下 javascript 视图模型(需要重构,但我希望首先让一切正常运行),并且设置是一个 MessagesViewModel ,它包含一个 MessageViewModels 的集合,MessageViewModel包含一个FeedbackViewModels的集合。发布新消息时,一切正常,集线器回调并更新 UI。问题是当我向评论添加反馈时,反馈会保留在数据库中,但不会调用回调 - 请参阅代码:

public bool AddMessageFeedback(string txtFeedbackComments, string hdnMessageId, int userId)
    {
        bool result = false;
        try
        {
            var message = new Message
                {
                    SDUID = userId,
                    MessageText = txtFeedbackComments,
                    MessageDate = DateTime.Now.Date,
                    MessageTime = Convert.ToDateTime(DateTime.Now.TimeOfDay.ToString()),
                    Poster = UserManager.GetItem(userId),
                    MessageDateAsString = DateTime.Now.Date.ToString(),
                    MessageTimeAsString = DateTime.Now.TimeOfDay.ToString(),
                    MessageDay = DateTime.Now.DayOfWeek.ToString()
                };

            MessageManager.AddMessageFeedback(message, Convert.ToInt64(hdnMessageId));

            Clients.All.messageFeedbackAdded(message);
            result = true;
        }
        catch (Exception)
        {
            Clients.Caller.raiseError("Unable to add feedback.");
        }

        return result;
    }

视图模型

$(function () {

    $(function () {

        function messageFeedbackViewModel(feedbackText, poster, messageDay, messageDate, messageTime, owner) {
            this.poster = poster;
            this.feedbackText = feedbackText;
            this.datePosted = messageDay.substr(0, 3) + ', ' + messageDate.substr(0, 10) + ' ' + messageTime.substr(0, 5);

            var self = this;
        }

        function messageViewModel(MessageID, messageText, SDUID, SportID, poster, sport, feedback, messageDate, messageDay, messageTime, owner) {
            this.hub = $.connection.messagesHub;

            //message variables, initialised from params
            this.MessageID = MessageID;
            this.SDUID = SDUID;
            this.SportID = SportID;
            this.poster = poster;
            this.messageText = messageText;
            this.sport = sport;

            this.datePosted = messageDay.substr(0, 3) + ', ' + messageDate.substr(0, 10) + ' ' + messageTime.substr(0, 5);

            //message feedback collection
            this.messageFeedback = ko.observableArray([]);

            //html variables
            this.newMessageFeedback = ko.observable();

            //reference to message feedback collection
            var messageFeedback = this.messageFeedback;

            var self = this;
            var notify = true;

            //callback from server side hub
            this.hub.client.messageFeedbackAdded = function (newMessageFeedback) {
                self.messageFeedback.push(new messageFeedbackViewModel(newMessageFeedback.MessageFeedbackText, newMessageFeedback.Poster, newMessageFeedback.MessageFeedbackDay, newMessageFeedback.MessageFeedbackDateAsString, newMessageFeedback.MessageFeedbackTimeAsString, self));
            };

            //build message feedback VM's
            if (feedback){
                if (feedback.length > 0) {
                    var mappedFeedbackMessages = $.map(feedback, function (feed) {
                        return new messageFeedbackViewModel(feed.MessageFeedbackText, feed.Poster, feed.MessageFeedbackDay, feed.MessageFeedbackDateAsString, feed.MessageFeedbackTimeAsString, self);
                    });
                    messageFeedback(mappedFeedbackMessages);
                }
            }

            //client side post
            this.createMessageFeedback = function () {
                var innerMessageFeedback = this.newMessageFeedback();
                var userId = $('#userID').val();
                var messageId = this.MessageID;
                this.hub.server.addMessageFeedback(innerMessageFeedback, messageId, userId).done(function () {
                    console.log('message saved!');
                }).fail(function (error) {
                    console.warn(error);
                });
                this.newMessageFeedback('');
            };
        }

        function messagesViewModel() {
            this.hub = $.connection.messagesHub;

            //messages collection
            this.messages = ko.observableArray([]);

            //html variables
            this.newMessageMessageID = ko.observable();
            this.newMessageSDUID = ko.observable();
            this.newMessageSportID = ko.observable();
            this.newMessagePoster = ko.observable();
            this.newMessageMessageText = ko.observable();

            //reference to messages collection
            var messages = this.messages;

            var self = this;
            var notify = true;
            var userId = $('#userID').val();

            //load messages, calling server side hub method
            this.init = function () {
                this.hub.server.getAll(userId);
            };

            //callback from server side hub sending messages to client
            this.hub.client.allMessagesRetrieved = function (allMessages) {
                var mappedMessages = $.map(allMessages, function (message) {
                    return new messageViewModel(message.MessageID, message.MessageText, message.SDUID, message.SportID, message.Poster, message.Sport, message.Feedback, message.MessageDateAsString, message.MessageDay, message.MessageTimeAsString, self);
                });

                messages(mappedMessages);
            };

            //callback from server side hub sending error messages to client
            this.hub.client.raiseError = function (error) {
                $("#error").text(error);
            };

            //call back from server side hub sending new message and pushing to collection
            this.hub.client.messageCreated = function (newMessage) {
                messages.splice(0, 0, new messageViewModel(newMessage.MessageID, newMessage.MessageText, newMessage.SDUID, newMessage.SportID, newMessage.Poster, newMessage.Sport, newMessage.Feedback, newMessage.MessageDateAsString, newMessage.MessageDay, newMessage.MessageTimeAsString, self));
            };

            //client side method from form post
            this.createMessage = function () {
                var selectedSport = $('#ddlSport option:selected').text();

                var message = { messageText: this.newMessageMessageText(), SDUID: userId, SportID: this.newMessageSportID(), Sport: selectedSport };

                this.hub.server.add(message).done(function () {
                    console.log('message saved!');
                }).fail(function (error) {
                    console.warn(error);
                });

                this.newMessageMessageText('');
                this.newMessageSDUID('');
                this.newMessageSportID('');
                this.newMessagePoster('');
            };
        }

        //set up the viewmodel
        var viewModel = new messagesViewModel();
        ko.applyBindings(viewModel);

        //call to initialise
        $.connection.hub.start(function () {
            viewModel.init();
        });
    });
});

任何帮助将不胜感激,谢谢。

4

1 回答 1

1

问题是您hub.client.messageFeedbackAdded在启动集线器连接后添加回调。

hub.client.messageFeedbackAdded当您创建一个新的回调时会添加回调,该回调messageViewModel会在allMessagesRetrievedmessageCreated触发时发生。这两个事件都在您的集线器连接开始后发生。

如果您真的想在开始连接后添加客户端集线器方法,您可以使用hubProxy.on( eventName, handler(args...)).

$.connection.messagesHub.on("messageFeedbackAdded", function (newMessageFeedback) { /*...*/ });

然而,这不是你应该做的。在与,和一起调用之前,您应该hub.client.messageFeedbackAdded只定义一次。$.connection.hub.startallMessagesRetreivedraiseErrormessageCreated

您需要将父消息 ID(可能hdnMessageId在服务器上)传递给客户端,messageFeedbackAdded以便客户端知道要将反馈添加到哪条消息,但无论如何消息 ID 都是必需的。

如果您使用hubProxy.oninside of为每条消息messageViewModel添加一个新的处理程序,那么无论反馈实际留给哪messageFeedbackAdded条消息,每次后续调用都会调用您的处理程序。Clients.All.messageFeedbackAdded(message);这意味着您的客户会显示每条新添加的反馈,每条消息显然不是您想要的。

于 2013-04-09T02:42:11.857 回答