For AI agents: the complete documentation index is available at /apps-plugin/docs/llms.txt, the full documentation bundle is available at /apps-plugin/docs/llms-full.txt, and this page is available as Markdown at /apps-plugin/docs/js-api/custom/createCustomEvent.md.

createCustomEvent

创建一组用于发送和监听自定义事件的函数。

支持版本

前端库版本不低于 0.0.1。

支持平台

平台支持情况
Android支持
iOS支持
PC支持
HarmonyOS不支持

支持场景

场景支持情况
页面支持
卡片支持

接入准备

前置条件

  • 发送端与接收端需使用相同的事件名称和参数结构

使用说明

  • 为事件名称添加业务命名空间,并在不再监听时调用注册函数返回的注销函数。

调用方式

同步 API

createCustomEvent<Params extends object>(name: string, options?: CustomEventOptions<Params>): [CustomEventCaller<Params>, CustomEventHandlerRegistry<Params>]

入参

名称类型必填默认值约束说明
namestring是--事件名称。建议添加业务命名空间,避免与其他事件重名。
options.paramsTypeGuardTypeGuard<object, Params>否--接收端的参数类型守卫。返回 `false` 时会忽略当前事件,不调用已注册的处理函数。

调用示例

import { createCustomEvent } from '@doubao-dev/framework/api';

interface TestEventParams {
  input: string;
}

const [emitEvent, onReceiveEvent] =
  createCustomEvent<TestEventParams>('example.testEvent');

const unregister = onReceiveEvent((params) => {
  console.log(params.input);
});

emitEvent({ input: 'test' });
unregister();

返回值

返回一个元组,第一项用于发送事件,第二项用于注册事件处理函数。