Ace Editor添加命令:如何调用外部自定义函数?
解决Ace Editor快捷键调用外部函数的this指向问题
问题出在Ace命令的exec回调函数里的this指向不是你外部的上下文(比如组件实例),而是Ace的命令对象本身,所以找不到handleFileUpdate方法。下面是几种可行的解决方式:
方法1:使用箭头函数
箭头函数会继承外部作用域的this,直接替换回调函数即可:
this.editor.commands.addCommand({ name: 'save', bindKey: {win: "Ctrl-S", "mac": "Cmd-S"}, exec: (editor) => { this.handleFileUpdate(); } });
方法2:提前保存外部的this
用变量把外部上下文的this存起来,在回调里引用这个变量:
const self = this; this.editor.commands.addCommand({ name: 'save', bindKey: {win: "Ctrl-S", "mac": "Cmd-S"}, exec: function(editor) { self.handleFileUpdate(); } });
方法3:用bind绑定this
通过bind方法把回调函数的this强制绑定到外部上下文:
this.editor.commands.addCommand({ name: 'save', bindKey: {win: "Ctrl-S", "mac": "Cmd-S"}, exec: function(editor) { this.handleFileUpdate(); }.bind(this) });
这三种方法都能让Ace的快捷键命令正确调用你自定义的handleFileUpdate函数。
内容的提问来源于stack exchange,提问作者user1519054
相关产品推荐
相关产品推荐

