Skip to content

Instantly share code, notes, and snippets.

@sb8244
Created January 23, 2022 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sb8244/d7104807cd0db510e251a67981161cb5 to your computer and use it in GitHub Desktop.
Save sb8244/d7104807cd0db510e251a67981161cb5 to your computer and use it in GitHub Desktop.
/**
* This example is just copy/pasted from my code base. The gist of it is that `this.pushEventTo` on the hook
* will send an event over the LiveView channel that is processed by the component/LiveView that's mounted at
* that element.
*
* I recommend using pushEventTo instead of pushEvent because I've run into situations where the event gets sent
* to the incorrect component or LiveView.
*/
const GeneratePDFButton = {
mounted() {
const target = this.el.getAttribute('phx-target') || this.el
// @ts-ignore This is a webpack import, not a ES2020
import(/* webpackChunkName: "pdf-kit-lv" */ '../entry/pdf-kit-lv').then((module) => {
this.pdfToImage = module.default.pdfToImage
}).catch(console.error)
this.handleEvent("generate_pdf_cover_image", (data: GeneratePDFButtonPayload) => {
if (!this.pdfToImage) { return }
this.pushEventTo(target, 'ui.cover_image_state', { state: "loading" })
this.pdfToImage(data.url).then((imgDataURL: string) => {
this.pushEventTo(target, 'ui.set_cover_image', { data: imgDataURL })
}).catch(() => {
this.pushEventTo(target, 'ui.cover_image_state', { state: "error" })
})
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment