Как исправить плагин mentionsInput, не работающий при использовании в двух местах в представлении cshtml - PullRequest
0 голосов
/ 11 октября 2019

У меня есть секция комментариев, где я использую комбинацию knockoutjs и плагина jquery.mentionsInput, чтобы включить упоминания других людей в комментариях и уведомить их. При комментировании это работает отлично, вы можете увидеть список людей, они становятся уведомленными. Но у меня также есть кнопка «Ответить», которая появляется при нажатии на нее. Структура одинакова для комментирования, та же текстовая область и так далее. но здесь сценарий упоминаний вообще не запускается.

Я попытался создать дубликаты тех же методов в сценарии упоминаний, только изменив имена методов и указав их на другие классы, например: оригинальные сценарии указываютна '$ (' textarea.mention ') и ответ textarea на' $ ('textarea.mention-reply'), но без игры в кости ..

Я попытался создать копию двух скриптов плагина и css,замена всех классов 'mentionsInput' и 'упоминания' на классы 'replyInput' и 'reply'. Никаких кубиков ..

Текстовая зона ответа скрыта в шаблоне, который я показываю, если вы нажмете кнопку «ответить», я попытался переместить его из шаблона, добавив его непосредственно в структуру html. Никаких кубиков ..

Дело в том, что если я заменил исходный textarea.mention на textarea.mention-reply и НЕ ИМЕЕТ ДРУГИХ ДРУГИХ классов в другом textarea, это работает. Это подтверждает, что копия плагина работает. Кажется, они просто не могут работать в одно и то же время / в одном и том же виде?

Оригинальный скрипт:

$(function () {

    $('textarea.mention').mentionsInput({
        onDataRequest: function (mode, query, callback) {

            $.when($.getJSON("/search/PeopleMention", { searchTerm: query }))
                .done(function (dataUsers) {
                    data = $.map(dataUsers.users,
                        function (item) {
                            return {
                                'id': item.id,
                                'name': '@' + item.firstname + ' ' + item.lastname,
                                'display': item.firstname + ' ' + item.lastname,
                                'avatar': item.image,
                                'type': 'contact',
                                'link': '/Info/Profilsida/?CurrentUser=' + item.id
                            };
                        });
                    data = _.filter(data, function (item) { return item.display.toLowerCase().indexOf(query.toLowerCase()) > -1 });
                    callback.call(this, data);
                });
        }
    });


    $('.comment-button').click(function () {
        $('textarea.mention').mentionsInput('getMentions', function (data) {
            var ids = "";
            var names = "";
            $.each(data,
                function (i) {
                    names += this.name + ';';
                    ids += this.id + ';';
                });
            $('.names-container').text(names);
            $('.notification-container').text(ids);
        });
    });
});

Копия выглядит точно так же, но имеет:

$('textarea.mention-reply').mentionsReply .... 

$('.mentions-reply-button').click .... 

Соответствующая часть скрипта knockoutjs:

function CommentsModel() {
    var that = this;

    that.replyToId = ko.observable(0);
    that.newCommentText = ko.observable();
    that.comments = ko.observableArray();

    that.updateComments = function (comments) {
        that.comments(that.sortComments(comments));
    };

    that.addComment = function () {

        var mentionsArray = matchMentionsWithNamesInPostComment();
        var encodedCommentText = '';

        if (mentionsArray.length > 0) {
            that.newCommentText(addLinksToMentionsInComment(that.newCommentText(), mentionsArray));
            encodedCommentText = encodeURIComponent(that.newCommentText());
        }

        var mentions = $('.notification-container').text();
        $.ajax({
            url: '/socialfunctions/addcomment/',
            type: 'POST',
            data: { id: $('#CurrentPageId').val(), comment: encodedCommentText == '' ? that.newCommentText() : encodedCommentText, mentions: mentions ,parentId: that.replyToId() }
        })
            .done(function (result) {
                    ........
            });
    };

    that.post = function() {
        setTimeout(function () {
            that.addComment();
        }, 500);
    };


    that.clickedReply = function (comment) {
        if (that.replyToId() === 0 || that.replyToId() !== comment.Id) {
            that.replyToId(comment.Id);
        } else {
            that.cancelReply();
        }
    };

    that.cancelReply = function () {
        that.replyToId(0);
        that.newCommentText('');
    };

    that.deleteComment = function (comment) {
            .....
    };
}

Представление:

    var clientResources = ServiceLocator.Current.GetInstance<IRequiredClientResourceList>();
    clientResources.RequireStyle("\\Static\\css\\jquery.mentionsInput.css").AtHeader();
    clientResources.RequireStyle("\\Static\\css\\jquery.mentionsReply.css").AtHeader();
    clientResources.RequireScript("\\Scripts\\site\\underscore-min.js").AtFooter();
    clientResources.RequireScript("\\Scripts\\jQuery\\jquery.elastic.source.js").AtFooter();
    clientResources.RequireScript("\\Scripts\\jQuery\\jquery.mentionsInput.js").AtFooter();
    clientResources.RequireScript("\\Scripts\\jQuery\\jquery.mentionsInputInit.js").AtFooter();
    clientResources.RequireScript("\\Scripts\\jQuery\\jquery.mentionsReply.js").AtFooter();
    clientResources.RequireScript("\\Scripts\\jQuery\\jquery.mentionsReplyInit.js").AtFooter();

    <div id="comments">
        <div class="clearfix">
            <div class="form-group">

                <h4>Kommentera</h4>
                <p class="infotext">Please write a comment</p>
                <textarea data-bind="visible: replyToId() == 0, textInput:newCommentText" class="mention form-control fullwidth" maxlength="4000"></textarea>
            </div>
            <div class="button-div">
                <span style="display: none;" class="notification-container"></span>
                <span style="display: none;" class="names-container"></span>
                <a href="/" data-bind="visible: replyToId() == 0, click:post" class="comment-button button">Send</a>
            </div>
        </div>
        <script type="text/html" id="reply-template">
            <div class="clearfix" data-bind="visible:$root.replyToId() == Id">
                <div class="form-group">
                    <h5>Svara <span data-bind="text: UserFullName"></span></h5>
                    <textarea data-bind="textInput:$root.newCommentText" class="mention-reply form-control fullwidth" maxlength="4000"></textarea>
                </div>
                <div class="button-div">
                    <a href="/" data-bind="click:$root.post" class="mentions-reply-button button">Send</a>
                    <a href="/" data-bind="click:$root.cancelReply" class="button">Cancel</a>
                </div>
            </div>
        </script>
        <div data-bind="visible:comments() == undefined || comments().length == 0">
            Right now there are no comments. Be the first to comment!
        </div>

        <div data-bind="foreach:comments">
            <div class="comment clearfix" data-bind="css: { reply: ParentId > 0 }">
                <div class="info">
                    <a data-bind="text:UserFullName, attr:{href:UserProfilePageLink}"></a>
                    <span class="date" data-bind="text: moment(CreateDate).format('YYYY-MM-DD')"></span>
                    <a class="reply-button pull-right" data-bind="visible: ParentId == 0, click: $parent.clickedReply">Reply</a>
                </div>
                <div data-bind="html:Comment, attr: { 'id': Id }"></div>
                @if (EPiServer.Security.PrincipalInfo.HasAdminAccess)
                {
                    <a href="#" class="button remove pull-right" data-bind="click:$parent.deleteComment">Remove</a>
                }
                <div class="reply" data-bind="template: { name: 'reply-template', data: $data }"></div>
            </div>
        </div>
    </div>

Я ожидаю, что плагин упоминаний будет работать в обеих текстовых областях, но он работает только в комментарииtextarea, не ответ textarea. Это никогда не срабатывает. Без ошибок ничего. Опять же, обе версии скрипта работают в первой текстовой области, и ни одна из них не работает в текстовой области ответа.

1 Ответ

0 голосов
/ 11 октября 2019

Я нашел ответ здесь:

JQuery: выбор динамически создаваемых элементов и отправка в Firebase

Создан div ".reply-container" для циклакомментарии (которые также отображают шаблон ответа) обернут сценарий в

$('#reply-container').on('click', '.reply-button', function () { ... }

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...