javascript - DOM 渲染成 svelte 后执行函数
问题描述
我需要运行在 DOM 完全更新后会发出事件的函数。我将 Svelte 与 Electron.js 结合起来。此页面用作 PDF 生成器,它从主进程加载数据,然后自我更新,最后通知主进程所有内容都已加载,主进程截屏此内容(PDF 进程)。所以代码:
PDF进程渲染器:
onMount(() => {
// Asks for the data, emits event
ipc.send('PDFWindowReady');
});
ipc.on('PDFLoadContent',(event,data)=>{
// Gets the data, event listener
const content = data.data;
// Assigns the data to a particular variable
contractorEnterprise = content.contractor.enterprise;
contractorAddress = content.contractor.street;
contractorCity = content.contractor.city;
//long list of assignments
output = data.output;
// Renders empty PDF, that means, that DOM has not re-rendered yet
// I need to ensure that it has, then execute function below
//ipc.send('makePDF',data.output)
});
beforeUpdate(async () => {
// This doesn't work, empty PDF
await tick();
if (output) {
await tick();
ipc.send('makePDF',output);
console.log(output);
}
});
/*
afterUpdate(() => {
// This neither
if (output) {
ipc.send('makePDF',output)
}
});
*/
ipc.on('PDFCreated',()=>{
// after PDF is generated, window will be closed
/* I even tried timeouts, but that is unreliable and could cause unloaded content
on big data load */
//setTimeout(() => {
window.close()
//},1000);
});
电子.js(main.js):
ipcMain.on('makePDF', (event,aux)=>{
const pdfPath = path.join(appRoot.pdfPath,aux.file);
const content = BrowserWindow.fromWebContents(event.sender);
content.webContents.printToPDF({
pageSize: "A4",
landscape: false
}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
event.sender.send('PDFCreated');
if (error) throw error;
new Notification({
title: 'PDF je hotové',
body: `Exportovanie dodacieho listu do ${pdfPath}.pdf bolo ukončené.`
}).show();
shell.openExternal(`file://${pdfPath}`);
console.log(`New delivery note:${pdfPath}`);
})
}).catch(error => {
console.log(error.message)
})
});
//triggered by primary process
ipcMain.on('openPDFWindow',(event,data)=>{
//opens new invisible browser window
fpt.createPDFWindow();
ipcMain.once('PDFWindowReady',(event)=>{
//as soon as is window ready event is emmited
event.sender.send('PDFLoadContent',data);
});
});
第 76 行的输出,console.log(output):
如您所见,我在页面加载后发送事件的任何尝试都不起作用。问题是它呈现空的PDF。以前我使用 jQuery 并通过超时解决了它,但这是愚蠢的容易出错的解决方案。我需要在渲染完所有内容后运行此函数:
ipc.send('makePDF',output)
问题是它渲染的是空的 PDF,看起来页面没有重新渲染并且截图太早了。有可靠的解决方案吗?
解决方案
推荐阅读
- google-apps-script - Apps 脚本 - 创建谷歌表单但在同一个数据库中得到响应(电子表格)
- azure - 如何通过 API 在 Azure Devops 中添加团队成员?Groups API 也不起作用
- firebase - 远程配置未从控制台更新
- html - 如何与验证一起动态循环表单控件名称
- bash - 用于在 zip 文件中查找最新文件匹配模式的 Bash 函数
- javascript - 获取 this.startBreak() 不是 react.js 中的函数错误
- android - 挂钩运行后下载的 dex 文件
- python - i need to make a confusion matrix for a CNN model
- delphi - Delphi - OpenDialog and DBGrid with Checkbox Click Problem
- python - 如何计算此代码的时间复杂度?