如何在JS中回调函数

时间:2019-08-24 11:41:25

标签: javascript froala

我正在为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);

然后我有一个带有回调的按钮插件,我想从其中调用该插件:

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

但是我随后收到错误消息:this.myPlugin is not a function

我要去哪里错了?

1 个答案:

答案 0 :(得分:0)

在回调中使用Javascript中的this关键字时,它很容易更改。要么绑定您的函数以使this被锁定到当前作用域,要么在作用域中使用另一个变量来跟踪它。

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

OR

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