Search code examples
javascriptfroala

How to callback a function in JS


I am building a custom plugin for Froala (https://www.froala.com/wysiwyg-editor):

// Custom plugin
(function(FroalaEditor) {
  // Add an option for your plugin.
  FroalaEditor.DEFAULTS = Object.assign(FroalaEditor.DEFAULTS, {
     myOption: false
  });

  // Define the plugin.
  // The editor parameter is the current instance.
  FroalaEditor.PLUGINS.myPlugin = function(editor) {
    // Private variable visible only inside the plugin scope.
    var private_var = "My awesome plugin";

    // Private method that is visible only inside plugin scope.
    function _privateMethod() {
      console.log(private_var);
    }

    // Public method that is visible in the instance scope.
    function publicMethod() {
      console.log(_privateMethod());
    }

    // The start point for your plugin.
    function _init() {
      // You can access any option from documentation or your custom options.
      console.log(editor.opts.myOption);

      // Call any method from documentation.
      // editor.methodName(params);

      // You can listen to any event from documentation.
      // editor.events.add('contentChanged', function (params) {});
    }

    // Expose public methods. If _init is not public then the plugin won't be initialized.
    // Public method can be accessed through the editor API:
    // editor.myPlugin.publicMethod();
    return {
      _init: _init,
      publicMethod: publicMethod
    };
  };
})(FroalaEditor);

I then have a button plugin with a callback, which I want to call the plugin from:

  FroalaEditor.DefineIcon('alert', {NAME: 'info', SVG_KEY: 'help'});
  FroalaEditor.RegisterCommand('alert', {
    title: 'Hello',
    focus: false,
    undo: false,
    refreshAfterCallback: false,
    callback: function () {
      this.myPlugin();
    }
  });

However I then get the error: this.myPlugin is not a function.

Where am I going wrong?


Solution

  • The this keyword in Javascript is prone to change when used in a callback. Either bind your function such that this is locked to the current scope, or use another variable in scope to keep track of it.

    function myCallback() {
        console.log(this.something);
    }
    let safeCallback = myCallback.bind(this);
    

    OR

    let that = this;
    function myCallback() {
        console.log(that.something);
    }