【问题标题】:Ace Editor - How to pass event dataAce Editor - 如何传递事件数据
【发布时间】:2014-10-31 18:27:41
【问题描述】:

我有一个扩展/折叠ace编辑器大小的功能,这是由一个按钮触发的。

编辑器获得焦点后,我需要触发“展开”。所以我做了这样的事情:

var editor = ace.edit("theeditor");
editor.on("focus", myFocusHandler);

myFocusHandler 看起来像这样:

var myFocusHandler = function(event) {
    // do some resize stuff here ...
    var toggleSizeButton = jQuery("expand-collapse-button");
    toggleSizeButton .toggleClass("glyphicon-resize-small");
    toggleSizeButton .toggleClass("glyphicon-resize-full");
}

到目前为止一切顺利。当我不得不重构我的代码以支持同一网页中的多个 ace 编辑器时,问题就开始了。使用 jQuery,我可以在事件处理程序中使用 this 来获取当前编辑器,然后使用 jQuery DOM 遍历函数获取与其相关的按钮。我怎样才能做到这一点(或将事件数据传递)到带有 Ace 的事件处理程序中?我想做这样的事情:

var myFocusHandler = function(event) {
    // do some resize stuff here...
    var theEditorDiv = jQuery(this); // I know this is wrong
    var toggleSizeButton = theEditorDiv.prev("div.toggle-button").find(".glyphicon");
    toggleSizeButton.toggleClass("glyphicon-resize-small");
    toggleSizeButton.toggleClass("glyphicon-resize-full");
}

jQuery(this) 的调用是错误的,原因有二:第一,this 未定义,第二,即使它是对编辑器的有效引用,它也不是 DOM 元素。

所以,这里有两个问题。

  1. 如何在事件处理程序中获取对 ace 编辑器对象的引用
  2. 如何获取内置 ace 编辑器的 div 元素。

有什么想法吗? Ace 编辑器 API 文档对此一无所知。

【问题讨论】:

    标签: javascript jquery ace-editor


    【解决方案1】:

    只有在事件监听器中获取事件目标的实验 api。你可以这样做

    var myFocusHandler = function(event, editor) {
        var theEditorDiv = jQuery(editor.container);
    

    【讨论】:

      【解决方案2】:

      Ace 将编辑器对象作为事件的第二个参数公开。您可以执行以下操作:

      HTML

      <h2>Editor 1</h2>
      <pre class="editor"></pre>
      
      <h2>Editor 2</h2>
      <pre class="editor"></pre>
      

      Javascript

      $('.editor').each(function() {
      
          var editor = ace.edit(this);
      
          editor.on('focus', function(event, editor) {
               $(editor.container).animate({ width: 500 });
          });
      
          editor.on('blur', function(event, editor) {
              $(editor.container).animate({ width: 300 });
          });
      
      });
      

      小提琴: http://jsfiddle.net/2t5ruscx/2

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多