这是指向羽毛笔编辑器工具栏

this is pointing to the quill editor toolbar

我用Quilljs for a textarea on my website. The standard editor don't support image upload to the server, so i have to implement a custom handler. In the documentation is written the following:

Handler functions will be bound to the toolbar (so using this will refer to the toolbar instance) and passed the value attribute of the input if the corresponding format is inactive, and false otherwise.

这对我来说实际上是个问题,我不知道如何以干净且 "right" 的方式解决它。我构建了一个 angular 应用程序,并且编写了一个用于图像上传的自定义处理程序。此自定义图像处理程序应在 angular 服务的帮助下将图像上传到服务器。数据服务在应用程序中全局提供,并且是我的组件的成员,我可以使用 this.dataService 访问它。但是点击工具栏中的图片上传图标后,this被绑定到工具栏,我无法再访问我的数据服务了。我可以避开工具栏的这个边界吗?

显式。假设我已经使用以下代码创建了一个羽毛笔编辑器:

this.editor = new Quill('#editor', {
      modules: { toolbar: "#toolbar"},
      placeholder: 'Some Placeholder',
      theme: 'snow'
});

现在我使用

向图像图标添加自定义处理程序
this.editor.getModule("toolbar").addHandler("image", imageHandler);

例如我的处理函数:

imageHandler(event) {
  this.dataService.addImage(event.file);
}

它使用我已经实施和测试过的数据服务。但是 this.dataService 不存在,因为 this 现在绑定到工具栏。我用组件的构造函数初始化了服务。

constructor(private dataService: DataService) {

}

当我在构造函数中调用this.dataService时,可以找到它并且边界很好,但是我需要在我的图像处理函数中调用它来将文件发送到服务器。

此致, 斯文

解决这个问题最简单的方法是改变

this.editor.getModule("toolbar").addHandler("image", imageHandler);

进入

this.editor.getModule("toolbar").addHandler("image", imageHandler.bind(this));

现在您可以在图像处理函数中访问组件 variables/members。工具栏不再是焦点