鹅毛笔编辑器,“ on”方法仅起作用一次

时间:2019-02-01 16:32:58

标签: quill

我有以下QuillEditor脚本(我有多个编辑器):

var editors = {};
        function editors() {
     var toolbarOptions = [
                        [{'list': 'ordered'}, {'list': 'bullet'}],
                    ];
                    data.forEach(function (el) {
                        editors[el] = new Quill(el['editor'], {modules: {toolbar: toolbarOptions}, theme: 'snow', scrollingContainer:el['quill'] });
                        editors[el].on('text-change', copyText(el['text'], editors[el]));
                    });
                }
        }
                function copyText(text, editor) {
                    text.innerHTML = editor.root.innerHTML;
                    console.log(text.innerHTML)
                }

要在后端使用它,我要将文本从编辑器复制到文本区域copyText(el['text']

我需要一直工作,但是它只能处理text / html,执行该功能时仅一次。我希望编辑器[el] .on('text-change',像事件监听器一样工作。

scrollingContainer,不滚动。我检查目标是否存在,是编辑器的父级。

1 个答案:

答案 0 :(得分:1)

我不确定这是否是错误的一部分,但是在}函数之后,您还有一个额外的editors

这里的主要问题是运行事件监听器而不是设置事件监听器,这就是为什么它只运行一次的原因。

因此将事件侦听器行更改为:

editors[el].on('text-change', function () {
    copyText(el['text'], editors[el]);
});

我一般不喜欢在其他函数中创建函数,尤其是在循环内部,因此我建议创建一个函数工厂函数,该函数将为每个元素创建一个新函数。

function createListener(text, editor) {
    return function(){
        copyText(text, editor);
    };
}

并这样称呼它:

editors[el].on('text-change', createListener(el['text'], editors[el]));