简体中文
emitEvent和onEvent
约 233 字小于 1 分钟
2025-09-22
emitEvent(eventName, option) 与 onEvent(eventName, handler) 用于实现插件内通信。
实现插件内通信的方法,两者需要配对使用。
emitEvent:发送事件的方法onEvent:监听事件的方法
参数
emitEvent(eventName, option)
| 参数 | 说明 | 类型 |
|---|---|---|
| eventName | 事件名称 | String |
| option | 事件的自定义参数 | Object |
onEvent(eventName, handler)
| 参数 | 说明 | 类型 |
|---|---|---|
| eventName | 事件名称 | String |
| handler | 事件的处理函数 | Function |
返回结果
无
代码示例
插件内:
module.exports = function (context, pluginService, pluginParam) {
return {
apply() {
return [
{
event: 'detail.render.after',
functional: function (pluginExecResult, options) {
console.log('custom plugin: detail.render.after exec')
// 发送事件
context.emitEvent('detail-render-after', {test: 123})
}
}
]
}
}
}组件内:
Component({
lifetimes: {
attached() {
// 接收插件发送的事件
this.data.context.onEvent('detail-render-after', option => {
console.log(option) // {test: 123}
// do something
})
}
}
})注意
onEvent()方法仅可监听当前详情页生命周期内emitEvent()方法发送的事件方法。onEvent()方法监听的事件名要跟emitEvent()方法发送的事件名相同。
