简体   繁体   中英

this is pointing to the quill editor toolbar

I use 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.

This is actually a problem for me and i dont know how to resolve it in a clean and "right" way. I built an angular application and i have written a custom handler for image uploading. This custom image handler should upload the image with the help of an angular service to the server. The data service is globally provided in the app and a member of my component and i can access it with this.dataService . But after clicking the image upload icon in the toolbar, this is bound to the toolbar, i can't access my data service anymore. Can i avoid this boundary to the toolbar?

In explicit. Assume i have created a quill editor with the following code:

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

Now i add a custom handler to the image icon with

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

and my handler function for instance:

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

which uses the dataService which i've already implemented and tested. But this.dataService don't exists because this is now bind to the toolbar. I initialized the service with the constructor of the component.

constructor(private dataService: DataService) {

}

When i call this.dataService in the constructor, then it can be found and the boundary is fine, but i need to call it in my image handler function to send the file to the server.

Best regards, Sven

The easiest way to solve this problem is to change

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

into

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

now you can access your components variables/members in your image handler function. The toolbar have not anymore the focus.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM