将 CodeMirror 实现到 Widget 后端表单而不更新文本区域

Implementing CodeMirror into Widget backend form not updating texarea

我正在努力思考这在我试图创建的小部件(类似于自定义 HTML 小部件)的管理后端的 wordpress 中的实际工作原理。我已经阅读了一些教程,但信息似乎发生了变化,我觉得我只是把自己弄糊涂了。

初始化 codemirror 时一切正常,它应用于文本区域,但我遇到的错误是:

  1. 当新 html 被输入 codemirror 时,小部件的保存按钮不会激活。
  2. 如果我更改另一个字段以激活保存按钮,则不会发送或保存来自 codemirror 的数据。

    (function ($) {
        $(document).ready( function(){
            var editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
            editorSettings.codemirror = _.extend(
                {},
                editorSettings.codemirror,
                {
                    lineNumbers: true,
                    mode: "text/html",
                    indentUnit: 2,
                    tabSize: 2,
                    autoRefresh:true,
                }
            );
            var editor = wp.codeEditor.initialize( $('#<?php echo $textarea_id; ?>'), editorSettings );  
        });
    })(jQuery);
    </script>
    

    我也试过添加:

     $(document).on('keyup', '.CodeMirror-code', function(){
          editor.codemirror.save();
          $('#<?php echo $textarea_id; ?>').html(editor.codemirror.getValue());
      });
    

但是当我通过 console.log

显示时 editor.codemirror.getValue() return 是空的

Textarea 代码

   <p>
       <label for="<?php echo $textarea_id; ?>"><?php _e( 'Locked Content:' ); ?></label>
       <textarea id="<?php echo $textarea_id; ?>" name="<?php echo $this->get_field_name( 'locked-content' ); ?>" class="widefat"><?php echo esc_textarea( $instance['locked-content'] ); ?></textarea>
    </p>

任何帮助(正确教程的链接、建议等)将不胜感激 JS 不是我最擅长的语言。

我相信这归结为我是个白痴大声笑我正在从另一个小部件调用相同的代码块,因为我试图将两个小部件文本区域都变成代码镜像。

我更改了 2 个变量的名称,以便更具体地针对小部件,例如:

var editorSettings    
var editor

更改为:

var cm_editorSettings    
var cm_editor

这让我得到了 cm.editor.codemirror.getValue() 和 return 的实际值。仍然不确定这是否是实现它的正确方法,所以如果我错了请纠正我,但目前更新文本区域和启用保存按钮的工作代码如下

<script type="text/javascript">
(function ($) {
    $(document).ready( function(){
          var cm_editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
            cm_editorSettings.codemirror = _.extend(
                {},
                cm_editorSettings.codemirror,
                {
                    lineNumbers: true,
                    mode: "text/html",
                    indentUnit: 2,
                    tabSize: 2,
                    autoRefresh:true,
                }
            );
        var cm_editor = wp.codeEditor.initialize($('#<?php echo $textarea_id; ?>') , cm_editorSettings );
        $(document).on('keyup', '.CodeMirror-code', function(){
            $('#<?php echo $textarea_id; ?>').html(cm_editor.codemirror.getValue());
            $('#<?php echo $textarea_id; ?>').trigger('change');
        });

    });
})(jQuery);