请问如何拆分`export const registerIpcMainHandlers = () => {...}`里面的方法呢?

我目前有一个文件(mainHandler.ts),里面有如下内容:

export const registerIpcMainHandlers = () => {
  ipcMain.on('message1'  , (event, data) => {
    console.log(`Message received from ${event.sender.id}: ${data}`);
    event.sender.send('response', 'Response message from main process.');
  });

  ipcMain.on('message2'  , (event, data) => {
    console.log(`Message received from ${event.sender.id}: ${data}`);
    event.sender.send('response', 'Response message from main process.');
  });
  ...
}

现在我想要拆分里面的一些监听方法到其他文件去(例如:subHandlers/handler1.ts):

mainHandler.ts
subHandlers/
  handler1.ts

应该怎么做呢?应该如何把subHandlers/handler1.ts中的on方法们引入到:registerIpcMainHandlers里面去呢?

阅读 2.3k
2 个回答
// subHandlers/handler1.ts
import { ipcMain } from 'electron';

export const handleMessage1 = () => {
  ipcMain.on('message1', (event, data) => {
    console.log(`Message received from ${event.sender.id}: ${data}`);
    event.sender.send('response', 'Response message from main process.');
  });
};

export const handleMessage2 = () => {
  ipcMain.on('message2', (event, data) => {
    console.log(`Message received from ${event.sender.id}: ${data}`);
    event.sender.send('response', 'Response message from main process.');
  });
};
// mainHandler.ts
import { handleMessage1, handleMessage2 } from './subHandlers/handler1';

export const registerIpcMainHandlers = () => {
  handleMessage1();
  handleMessage2();
  // ...
};

楼上的方法已经很明确了,不过题主的描述貌似有一些分歧:

简单概述下:
想要拆分A.ts里面的方法到XX/B.ts中,
题主问的是:

应该如何把XX/B.ts中的on方法们引入到:A.ts里面去呢?

猜测你想问的应该是

将A.ts文件中的方法拆分,在XX/B.ts中引入

如果不想改动 registerIpcMainHandlers方法,又想拆分,又想复用,可以这样

// mainHandler.ts
import { ipcMain } from 'electron';
export const registerIpcMainHandlers = () => {
  ipcMain.on('message1'  , (event, data) => {
    console.log(`Message received from ${event.sender.id}: ${data}`);
    event.sender.send('response', 'Response message from main process.');
  });

  ipcMain.on('message2'  , (event, data) => {
    console.log(`Message received from ${event.sender.id}: ${data}`);
    event.sender.send('response', 'Response message from main process.');
  });
  ...
}

// 拆分的方法
export const handleMessage = (msgName) => {
  ipcMain.on(msgName, (event, data) => {
    console.log(`Message received from ${event.sender.id}: ${data}`);
    event.sender.send('response', 'Response message from main process.');
  });
};

引入这里就不再赘述了~【PS:也有可能是我理解的有偏差】

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏