Search code examples
editorace-editorcustom-function

Ace Editor AddCommand - How to invoke external function


I am using Ace editor in a web app I am developing. I have a Save button that calls a function I wrote called handleFileUpdate(). But, I also want the user to be able to save the contents by a keyboard shortcut.

Here is my current code for the Ace keybinding:

    this.editor.commands.addCommand({
      name: 'save',
      bindKey: {win: "Ctrl-S", "mac": "Cmd-S"},
      exec: function(editor) {
        this.handleFileUpdate();
      }
    });

where this.handleFileUpdate() is a function in my own code.

When the command is invoked, Ace throws this error:

TypeError: this.handleFileUpdate is not a function. (In 'this.handleFileUpdate()', 'this.handleFileUpdate' is undefined)

I understand that this.handleFileUpdate() is not visible to Ace.

My question is: how is it possible for an Ace command to invoke an external function? Or put another way, how is it possible to provide a custom function to Ace so it can invoke it when Ctrl-S is pressed?


Solution

  • This is not so much a question about ace, as about this handling in javascript.

    In your example this in the internal function is the object on which the method is defined.

    As a workaround you can use an arrow function.

        this.editor.commands.addCommand({
          name: 'save',
          bindKey: {win: "Ctrl-S", "mac": "Cmd-S"},
          exec: (editor) => {
            this.handleFileUpdate();
          }
        })
    ``~