使用CKEditor在setData和模式更改时重置侦听器事件

时间:2016-09-21 18:35:55

标签: javascript events ckeditor listener document

每当我的脚本调用setData或更改模式(" source"," WYSIWYG")时,就不再调用我指定的事件的监听器。

研究告诉我为什么和我一直在试验建议的解决方案(CKEDITOR.setData prevents attaching of events with .on function),包括来自官方文档(http://docs.ckeditor.com/#!/api/CKEDITOR.editor-event-contentDom)的解决方案,但是没有一个解决方案对我有用,如文档所述,以及我不明白为什么。

此处有其他人设法解决此问题吗?如果是这样,我将非常感激如何找到。

我们目前正在运行CKEditor的4.5.10版本。

感谢您的期待。 肯

示例:

<element name="text">
 <interleave>
  <data type="string">
    <param name="pattern">.+</pattern>
  </data>
  <zeroOrMore>
    <ref name="bold" /> 
  </zeroOrMore>
  <zeroOrMore>
    <ref name="italic" /> 
  </zeroOrMore>
  <zeroOrMore>
    <ref name="underline" /> 
  </zeroOrMore>    
 </interleave>
</element>

更新:这个解决方案(由Dekel建议)看起来应该可行。但是,我怀疑我没有正确实现它,因此Key Down事件没有触发。对此有任何想法:

// Works until setData() is called or until the view mode is changed ("WYSIWYG", "SOURCE).

ev.editor.document.on( 'keydown', function( evt )
{
    console.log("Key Down");
});

// This appears to be the recommended resolution however, this does not
    // work for me even prior to setData() being called of the view mode being changed.

    editor.on( 'contentDom', function() {
    var editable = editor.editable();

    editable.attachListener( editor.document, 'keydown', function() {
    console.log("Key Down"); // Never executed
        } );
    } );

更新:完整的代码示例。事件似乎不再发生:

for (var i in CKEDITOR.instances) {
    CKEDITOR.instances[i].on('contentDom', function() {
        CKEDITOR.instances[i].document.on('keydown', function(event) {
            console.log('key down')
        });
    });
}

1 个答案:

答案 0 :(得分:2)

花些时间了解问题所在,但我认为这是您正在寻找的解决方案。

每次DOM准备就绪时,您需要附加keydown事件。为此 - 您需要收听编辑器的contentDom事件,然后在编辑器的文档中注册keydown事件。

CKEDITOR.instances.editor1.on( 'contentDom', function() {
    CKEDITOR.instances.editor1.document.on('keydown', function(event) {
        console.log('key down')
    });
});
  

在此示例中,editor1是ckeditor实例的名称。

您可以查看此工作示例:
https://jsfiddle.net/gad701dc/

如果您有多个实例,则需要对它们进行循环并将其添加到每个实例中:

for (var i in CKEDITOR.instances) {
    CKEDITOR.instances[i].on('contentDom', function() {
        // The variable *this* here refers to the current instance of the ckeditor
        this.document.on('keydown', function(event) {
            console.log('key down')
        });
    });
}
  

您需要访问相关编辑器,您应该使用this代替CKEDITOR.instances[i],因为i变量将在调用回调函数之前发生变化。