Search code examples
javascripteventsace-editor

Listening to content changes in Ace editor


I have to listen to content changes in an Ace editor. I figured out many ways to do it, and I would like to know the best / most adequate / canonical way to do it.

  • I am only interested in content changes. The event handler should be fired when user types/deletes characters, and I don't need to know the content.
  • There is no "multi-editor": single editor session, no tabs. Though, for the future, supporting multiple sessions may be interesting, if there is no additional cost.

Questions:

  • Should I use Editor or EditSession?
  • If using the edit session, should I access it using the getter or directly the property? (getter should be the recommended one, but the property is exposed as well…)
  • Should I listen to "change" or "input"? Notes:
    • Native <textarea>'s use "input".
    • There are editor.on('input', ...), editor.on('change', ...), editSession.on('change', ...), but not editSession.on('input', ...).

API references:

Additional question: when trying editSession.on('change', () => ...), I noticed the callback receives a "delta" object, whereas the callback is expected to provide no parameters. If someone has an explanation for this…


Solution

  • You can use editor.session, editor.getSession() is kept for backwards compatibility.

    The difference between change and input events, is that change event is fired synchronously for each insertion or deletion, and provides delta object that allows to keep track of changes, update positions with changes, etc. Meanwhile the input event fires 50ms after a change, and is convenient for usecases where you just want to know that something have changed.